Design pattern to create validators. By wrapping TextInputs with Validators, we bind validation checks to events required, only customizing error messages and validation required.
- Material TextInputLayout support.
- OnFocusChange and onTextChanged events.
- Error messages customizable.
- Error handling callback.
- Provided Email Validator.
- Provided Phone Number Validator.
- Provided Password Validator (confirmation, upper, lower, digit, special, minimum characters).
- Android SDK 8.0+
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}
dependencies {
compile 'com.github.philip-bui:input-validator:1.0.0'
}
EditText email = (EditText) findViewById(R.id.email);
EmailValidator emailValidator = new EmailValidator(email);
emailValidator.setTextInputLayoutValidate(true);
emailValidator.setRequired(true, "Required email address"); // Error message on empty.
emailValidator.setLoseFocusValidate(true); // onFocusChange event validation binded.
if (emailValidator.validate()) {
... // Successful validation.
} else {
... // Unsucessful validation. Error messages / callbacks have been displayed.
}
Customization is easy. To create new Validation logic, just extend Validator.
public class PhoneNumberValidator extends Validator {
public PhoneNumberValidator(EditText editText) {
super(editText);
}
@Override
public String onValidate(String string, Context context) {
if (!Patterns.PHONE.matcher(string).matches()) {
return context.getString(R.string.av_phone_number_is_invalid);
}
return null;
}
}
Alternatively multiple Validators can be composed onto one (see ConfirmPasswordValidator), representing a checklist.
validateListener
Default: null
Interface when a success or error validation happens.
stopTypingValidate
Default: false
Whether to validate when the user stops typing.
loseFocusValidate
Default: true
Whether to validate when the user changes focus FROM the field.
showError
Default: true
Whether to show error messages. Useful to set false if you want to manually handle error messages.
textInputValidate
Default: false
Whether to show the error message on the parent TextInputLayout. If the parent of the EditText is not a TextInputLayout, it throws an Exception when set to true.
required
Default: false, "Required field"
Whether to return an error when empty. This is called before validate(), and also comes with a custom Error message.
Input Validator is available under the MIT license. See LICENSE for details.