In this tutorial, we will create or perform form validation in android studio at multiple fields. We will validate username, email, password, phone number, date of birth(age) and also gender validation. We will use Material design fields we already created in login and signup. We will also use radio buttons for gender and Calendar to get the age of the user.
Watch Youtube tutorial
Form Validation in android studio
To start the form validation we first have to understand the flow. If you want to create any of the design mentioned above or need to get resources then click here.
We will perform the validation individually for each field and create seprate function to perform validation. We will call all the functions from the main function or the function which only executes when user presses the button. So we will use this code below to call each function with single | to make sure that each function should be executed inside if() statement.
Inside OnClick function
if (!validateFullName() | !validateUsername() | !validateEmail() | !validatePassword()) {
return;
}
Validate Full Name
To start the form validation we first perform the validation of full name as it is at the top in design So, just copy this function created below.
Validate FullName
private boolean validateFullName() {
String val = fullName.getEditText().getText().toString().trim();
if (val.isEmpty()) {
fullName.setError("Field can not be empty");
return false;
} else {
fullName.setError(null);
fullName.setErrorEnabled(false);
return true;
}
}
Validate UserName
Inside the username validation we can add checks for spaces, size limits etc.
Validate UserName
private boolean validateUsername() {
String val = username.getEditText().getText().toString().trim();
String checkspaces = "Aw{1,20}z";
if (val.isEmpty()) {
username.setError("Field can not be empty");
return false;
} else if (val.length() > 20) {
username.setError("Username is too large!");
return false;
} else if (!val.matches(checkspaces)) {
sername.setError("No White spaces are allowed!");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
Validate Email
Email validation in most of the cases is already set up when we choose the type to email in XML but for more concern we can do it like this.
Validate Email
private boolean validateEmail() {
String val = email.getEditText().getText().toString().trim();
String checkEmail = "[a-zA-Z0-9._-]+@[a-z]+.+[a-z]+";
if (val.isEmpty()) {
email.setError("Field can not be empty");
return false;
} else if (!val.matches(checkEmail)) {
email.setError("Invalid Email!");
return false;
} else {
email.setError(null);
email.setErrorEnabled(false);
return true;
}
}
Validate Password
Password validation in android studio is most concer thing to do. So, I’ve added all the possible validations and you can use them by just uncommenting any line you need.
Validate Password
private boolean validatePassword() {
String val = password.getEditText().getText().toString().trim();
String checkPassword = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
//"(?=.*[@#$%^&+=])" + //at least 1 special character
"(?=S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
password.setError("Field can not be empty");
return false;
} else if (!val.matches(checkPassword)) {
password.setError("Password should contain 4 characters!");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
Validate Gender
As we are using radio buttons here to check the gender so we can validate if nothing selected.
Validate Gender
private boolean validateGender() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please Select Gender", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
Validate Age
We can add a age restriction like only the users with minimum of 18 years can register.
Validate Gender
private boolean validateAge() {
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int userAge = datePicker.getYear();
int isAgeValid = currentYear - userAge;
if (isAgeValid < 14) {
Toast.makeText(this, "You are not eligible to apply", Toast.LENGTH_SHORT).show();
return false;
} else
return true;
}
Validate Phone Number
Phone number validation can be enhanced if you know that you can targetting only one country but if the case is about all the coutries then It will be dificult to do that so we will add white spaces check here. We can also validate by checking the phone number from database.
Validate Gender
private boolean validatePhoneNumber() {
String val = phoneNumber.getEditText().getText().toString().trim();
String checkspaces = "Aw{1,20}z";
if (val.isEmpty()) {
phoneNumber.setError("Enter valid phone number");
return false;
} else if (!val.matches(checkspaces)) {
phoneNumber.setError("No White spaces are allowed!");
return false;
} else {
phoneNumber.setError(null);
phoneNumber.setErrorEnabled(false);
return true;
}
}