i have five editText fields and i want to validate if there is empty editText. my code is working, the problem is that when there is one empty field, error shows on all fields.
here is my code:
String one = firstname.getText().toString();
String two = lastname.getText().toString();
String three = email.getText().toString();
String four = address.getText().toString();
String five = mobile.getText().toString();
if(!TextUtils.isEmpty(one) && !TextUtils.isEmpty(two) &&
!TextUtils.isEmpty(three) &&!TextUtils.isEmpty(four) &&
!TextUtils.isEmpty(five)) {
Intent i = new Intent(main.this, next.class);
i.putExtra("first", one);
i.putExtra("last", two);
i.putExtra("email", three);
i.putExtra("mobile", four);
i.putExtra("address", five);
startActivity(i);
} else {
firstname.setError("First name cannot be empty");
lastname.setError("last name cannot be empty");
email.setError("email cannot be empty");
address.setError("address cannot be empty");
mobile.setError("mobile cannot be empty");
}
Try,
Boolean valid = true;
if ( TextUtils.isEmpty(one) ) {
firstname.setError("First name cannot be empty");
valid = false;
}
if ( TextUtils.isEmpty(two) ) {
lastname.setError("last name cannot be empty");
valid = false;
}
if ( TextUtils.isEmpty(three) ) {
email.setError("email cannot be empty");
valid = false;
}
if ( TextUtils.isEmpty(four) ) {
address.setError("address cannot be empty");
valid = false;
}
if ( TextUtils.isEmpty(five) ) {
mobile.setError("mobile cannot be empty");
valid = false;
}
if ( valid ) {
Intent i = new Intent(main.this, next.class);
i.putExtra("first", one);
i.putExtra("last", two);
i.putExtra("email", three);
i.putExtra("mobile", four);
i.putExtra("address", five);
startActivity(i);
}