Validate EditText fields in a couple of lines, with custom, scalable validations.
Valigator enables you to easily validate EditTexts with custom validations. Here's how you do that!
First you create your validators. The library supports 2 types of validators. One which doesn't have any external dependencies, and one which does. You can use the second type if your validation is dependant on external data.
val normalValidator = Validator("Optional Error Message") {
text.length < 5
}
val customValidator = Validator.Custom<RadioButton>("Custom Error Message") { button : RadioButton ->
button?.isChecked == true && text.contains("spaceX")
}
//Multiple errors in one validation
val multipleErrorValidator = Validator{
//it's a good idea to return true inside the checks, to tell the library you've already handled the error
if (this == null) {
error = "Null object"
true
} else if (text.isEmpty()) {
error = "Text is empty"
true
} else false
}
The second kind of validation requires a class type to be specified. This is the type of the external data it will be expecting.
The second step is to enable the validator on EditText fields.
edit_text.setValidator(normalValidator)
edit_text_1.setValidator(normalValidator)
edit_text_2.setValidator(customValidator.addDependency(button_dependency))
edit_text_3.setValidator("Simple validation") {
text.isNotEmpty()
}
Important: For external dependancy validations it's required to add a dependency with the addDependency()
function. Only one dependency is supported, but it can be anything, for example, a list of views.
You can see the third EditText field which accepts a String and a function. That one is a third, extra kind of validation, which doesn't require any premade validators, and can validate fields on the go.
That's it! When you set up the validators, each time the text inside of the EditText field changes, the validation will be preformed.
Here's a preview of those fields:
You can manually download the library class and use it in your application.
dependencies {
implementation 'com.radoslav.valigator:valigator:$latest_version'
}
<dependency>
<groupId>com.radoslav.valigator</groupId>
<artifactId>valigator</artifactId>
<version>latest_version</version>
<type>pom</type>
</dependency>
Minimum Android SDK: API level 19
Radoslav Yankov @Radoslav_Y
If you spot a problem you can open an issue on the Github page, or alternatively, you can tweet me at @Radoslav_Y
FastList is released under the MIT License.