Source link: https://github.com/BrianHardyR/TextInputLayoutValidator
How to create simple validation for text input with Java Android?
TextInputLayoutValidator
This project provides a simple and streamlined way to validate TextInputLayoutEditText
Installation
- Add the JitPack repository to your build file
allprojects {
repositories {
... maven {
url https://jitpack.io
}
}
}
- Add the dependency
dependencies {
implementation com.github.BrianHardyR:TextInputLayoutValidator:1.1.2
}
How to
Simple Validation
val myinput = findViewById<TextInputLayout>(R.id.my_input) myinput.validate(
default = "my default text",
validators = listOf(
{
text -> t.isNotEmpty()
}
,
...
),
error = "my error text",
onValid = {
validText ->
// do something with the valid text
}
)
Using the Validation Object
Error message for each validation condition
val phoneNumberValidator = TextInputValidator(
defaultString = "My default text",
validators = listOf(
{
text -> (text.length > 12) to "Length must be greater than 12"
}
,
{
text -> text.startsWith( + ) to "Input must start with + "
}
,
...
) )
Single error message
val phoneNumberValidator = TextInputValidationObj(
default = "My default text",
error = "Please enter a valid phone number",
validators = listOf(
{
text -> text.length > 12
}
,
{
text -> text.startsWith( + )
}
,
...
) ) myinput.validate(phoneNumberValidator){
validText ->
// do something with the valid text
}
Validate input After setting the validation object on the TextInputLayout you can validate it anywhere on your code
myinput.valid() // Return a Boolean.