In this tutorial, you will learn how to validate form and show errors if something was missed. To validate form we'll use AwesomeValidation to declare validation style and add validations.
Add a following dependency in your project build
compile 'com.basgeekball:awesome-validation:1.3'
To display the error messages we need to define all the needed strings inside strings.xml file.
<resources>
<string name="name_required">Field name is requred</string>
<string name="email_error">Enter a valid email</string>
<string name="age_error">Enter a valid age</string>
</resources>
To validate the input modify the code as below.
AwesomeValidation v;
EditText etName, etEmail, etAge;
protected void onCreate(Bundle savedInstanceState) {
...
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etAge = (EditText) findViewById(R.id.etAge);
v = new AwesomeValidation(ValidationStyle.BASIC);
v.addValidation(this, R.id.etName, RegexTemplate.NOT_EMPTY, R.string.title_required);
v.addValidation(this, R.id.etEmail, Patterns.EMAIL_ADDRESS, R.string.email_error);
v.addValidation(this, R.id.etAge, "^[1-150]{1,3}$", R.string.age_error);
}
private void submitForm() {
if (v.validate()) {
//process data
}
}
Result
