Usage¶
Using this library boils down to this steps
- Create a validator object
Validator validator = new Validator();
- Add validation checks to the validator
// the editText objects to validate
EditText nameEditText = (EditText) editText.findViewById(R.id.name);
Spinner ageSpinner = (Spinner) editText.findViewById(R.id.spinner);
// ... using check objects
validator.addCheck(new NotEmptyCheck(nameEditText, "name cannot be blank");
validator.addCheck(new NotEmptyCheck(ageSpinner, "age cannot be blank");
Learn more about available checks
- Validate
To run the validations involve the validators
validate()
method.
validator.validate()
This method returns true
if the validation passed or false
if the validations failed.
Handle the errors¶
Incase of validation failure, the validation errors can be accessed via the
getErrors()
method.
This library comes with a convenience class ErrorRenderer
, which can be
used to easily display the validation errors.
- Displaying errors.
// the layout where we display any validation errors
LinearLayout errorSpace = (LinearLayout) findViewById(R.id.error_base);
errorSpace.removeAllViews();// clear space first
if (validator.validate()) {
// .. code to perform if validation passes
} else {
// show the errors if validation failed
// we use the renderer class to handle the display
ErrorRenderer errorRenderer = new ErrorRenderer(this, validator);
errorRenderer.render(errorSpace);
}
- Using ValidationListener to handle errors.
This version of validate()
accepts a ValidationListener
which has
onValidationSuccess
invoked when
validation is a success. onValidationFailed
invoked when validation fails methods.
// the layout where we display any validation errors
LinearLayout errorSpace = (LinearLayout) findViewById(R.id.error_base);
errorSpace.removeAllViews();// clear space first
validator.validate(new ValidationListener() {
@Override
public void onValidationSuccess(ValidatorInterface validatorInterface) {
// on success code
}
@Override
public void onValidationFailed(ValidatorInterface validatorInterface) {
// show the errors if validation failed
// we use the renderer class to handle the display
ErrorRenderer errorRenderer = new ErrorRenderer(MainActivity.this,
validatorInterface);
errorRenderer.render(errorSpace);
}
});