Validation - Krunal-Kevadiya/kotlin-common GitHub Wiki

Validation is a text validation library for Android developed in Kotlin. It supports text validation for String, EditText, TextView, AutoCompleteTextViewand Spinner. It comes with lots of built-in rules for validation such as email, password, credit cards, special character validations and so on.

Quick String Validation

For example, you can validate any email string like this:

var myEmailStr = "[email protected]"
var isValid = myEmailStr.validEmail<Int>()  // isValid will be true or false

// Or you can also validate with an error callback method
myEmailStr.validEmail<String>() {
    // This method will be called when myEmailStr is not a valid email.
    Toast.makeText(contex, it, Toast.LENGTH_SHORT).show()
}

Text View Validations

These built-in rules can also be applied on text views like EditText, TextView, AutoCompleteTextView and Spinner like this.

var myEditText = findViewById<EditText>(R.id.myEditText)
var isValid = myEditText.nonEmpty<String>()        // Checks if edit text is empty or not

// Or with error callback method like this
myEditText.nonEmpty<String>() {
    // This method will be called when myEditText is empty.
    myEditText.error = it
}

There are around 30+ built-in rules in the core module library. You can check all these in Rules page.

Multiple Validation Checks

Validation also supports multiple validation checks at same time using Validator class like this: // This example will check that whether user entered password has // atleast one number, one spcial character, and one upper case.

var txtPassword = findViewById<EditText>(R.id.txtPassword)
txtPassword.validator<String>()
           .nonEmpty()
           .atleastOneNumber()
           .atleastOneSpecialCharacters()
           .atleastOneUpperCase()
           .addErrorCallback { 
                txtPassword.error = it
                // it will contain the right message. 
                // For example, if edit text is empty, 
                // then 'it' will show "Can't be Empty" message
           }
           .check()

Create Your Own Custom Validation Checks

You can also add your own custom by extending BaseRule class.

class EmailRule<ErrorMessage>(
    var errorMsg: ErrorMessage? = null,
    clazz: Class<ErrorMessage>
) : BaseRule<ErrorMessage>(clazz) {
    // add your validation logic in this method
    override fun validate(text: String) : Boolean {
        // Apply your validation rule logic here
        return text.matches(Regex("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+"))
    }
    
    // Add your invalid check message here
    override fun getErrorMessage(): ErrorMessage? {
        return when {
            errorMsg != null -> errorMsg
            typed(kotlin.String::class.java, java.lang.String::class.java) -> "Invalid Email Address!" as? ErrorMessage
            typed(kotlin.Int::class.java, java.lang.Integer::class.java) -> R.string.vald_invalid_email_address as? ErrorMessage
            else -> throw MismatchErrorTypeException()
        }
    }

    override fun setError(msg: ErrorMessage?) {
        errorMsg = msg
    }
}

You can use this rule using Validator.addRule() method like this:

var myEditText = findViewById<EditText>(R.id.myEditText)
var myEditText.validator<String>()
    .addRule(EmailRule())
    .addErrorCallback { 
        // In case of invalid, this method will be called.
        // The 'it' will be "Please enter valid email address" message.
        myEditText.error = it
    }
    .check()

Applying Rules on Multiple Views/Strings

For example, your app has a long text input form where you have got lots of input views. You might perform checks in EasyValidation like this.

WRONG WAY

var edtFirstName = findViewById<EditText>(R.id.edtFirstName)
var edtLastName = findViewById<EditText>(R.id.edtLastName)
var edtEmail = findViewById<EditText>(R.id.edtEmail)
var edtPassword = findViewById<EditText>(R.id.edtPassword)

if (edtFirstName.nonEmpty<String>() && edtLastName.nonEmpty<String>() 
    && edtEmail.nonEmpty<String>()&& edtPassword.nonEmpty<String>()) {
    // All views are non-empty. You are safe to submit the data to server.
}
else {
    // Any one or more fields are empty. Show the error to the user
    // to fill the whole form.
    // You don't know which field is empty. So you might need to find it.
}

But, EasyValidation also provides you the collection extensions to make this easier.

RIGHT WAY

var edtFirstName = findViewById<EditText>(R.id.edtFirstName)
var edtLastName = findViewById<EditText>(R.id.edtLastName)
var edtEmail = findViewById<EditText>(R.id.edtEmail)
var edtPassword = findViewById<EditText>(R.id.edtPassword)

// Empty check
nonEmptyList<String>(edtFirstName, edtLastName, edtEmail, edtPassword) { view, msg ->
    view.error = msg
    // The view will contain the exact view which is empty
    // The msg will contain the error message 
}

// Min-length Check - all views should have atleast 5 characters
minLengthList<String>(5, edtFirstName, edtLastName, edtEmail, edtPassword) { view, msg ->
    view.error = msg
    // The view will contain the exact view which is less than 5 characters
    // The msg will contain the error message 
}

You can apply all the built-in rules just by adding List suffix in the rule name. For example, nonEmpty becomes nonEmptyList, the validEmail becomes validEmailList and so on.

Error and Success Callbacks

The Validator class provides callback methods with addErrorCallback() and addSuccessCallback() methods. For example:

var myNumber = "1234567"
var validator = Validator<String>(myNumber)

validator.startWithNumber()
    .addErrorCallback { msg ->
        // Do something here with the error.
        // The msg variable contains the error message
    }
    .addSuccessCallback {
        // Validation checks are passed. The text is valid.
        // Do anything with success case here.
    }
    .check()

Data-Binding with ObservableField

You can define ValidatedObservableField with two value. one is component value and second is onChange value. here onChange is enable/disable property for apply validation on text change time.

    val editTextPassword = bindValidator<String>("", true)
        .nonEmpty("Please enter your password.")
        .regex(".*[A-Z]+.*", "Must contain capital letters.")
        .regex(".*[0-9]+.*", "Must contain digits.")
        .regex(".*[a-z]+.*", "Must contain small letters.")
        .minLength(8, "Eight or more characters.")
        .maxLength(16, "No more then sixteen characters.")
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/edt_lay_password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_10sdp"
    app:errorEnabled="true"
    app:error="@{viewModel.editTextPassword.error ?? ``}"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/btnValidation">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:text="@={viewModel.editTextPassword.value}"
        android:hint="Password"/>

</com.google.android.material.textfield.TextInputLayout>

Also you have check on button click event then

    if(editTextPassword.check()) {
        Log.e(TAG, "True ${editTextEmail.getError()}")
    } else {
        Log.e(TAG, "False ${editTextEmail.getError()}")
    }

List of Extension Methods

Here is the list of all extension methods for String, EditText, TextView, AutoCompleteTextView and Spinner classes.

Method Description
validator() Returns the Validator object with text
nonEmpty() Returns true if the text is not empty. And returns false if text is empty.
minLength() Returns false if the length of text is less than given minimum length.
maxLength() Returns false if text length is greater than given length
validEmail() Returns true if text is a valid email address.
validNumber() Returns true if the text is any valid number
greaterThan() Returns false if the text is number less than the given target number
greaterThanOrEqual() Returns false if the text is number less than or equal to the given target number
lessThan() Returns false if the text is number greater than the given target number
lessThanOrEqaul() Returns false if the text is number greater than or equal to the given target number
numberEqualTo() Returns false if the text is a valid number and equal to the given target number
allUperCase() Returns false if at least one or more characters are lower case
allLowerCase() Returns false if at least one or more characters are upper case
atleastOneUperCase() Returns true if at least one or more characters are upper case
atleastOneLowerCase() Returns true if at least one or more characters are lower case
atleastOneNumber() Returns true if at least one or more characters are numbers
startWithNumber() Returns true if text starts with any number
startWithNonNumber() Returns false if text starts with any number
noNumbers() Returns false if the text any number or digit.
onlyNumbers() Returns false if text contains any alphabetic character
noSpecialCharacters() Returns true if text contain no special characters
atleastOneSpecialCharacters() Returns true if text contain at least one special characters
textEqaulTo() Returns false if the text is not equal to the given text
textNotEqualTo() Returns true if the text is not equal to the given text
startsWith() Returns true if the text starts with the given text
endsWith() Returns true if the text ends with the given text
contains() Returns true if the text contains the given text
notContains() Returns false if the text contains the given text
creditCardNumber() Returns true if the text is valid credit card number. This supports Visa, Master Card, American Express, Diners Club, Discover, and JCB.
creditCardNumberWithSpaces() Returns true if the text is valid credit card number with spaces between 4 characters. This supports Visa, Master Card, American Express, Diners Club, Discover and JCB.
creditCardNumberWithDashes() Returns true if the text is valid credit card number with dashes between 4 characters. This supports Visa, Master Card, American Express, Diners Club, Discover, and JCB.
validUrl() Returns true if the text is a valid URL
regex() Returns true if the text matches passed RegEx pattern.

List of Collection Extensions

The Collection extension methods' names are same as the extension methods names followed by List keyword. For example, validEmail() becomes validEmailList() and so on. These methods accept varargs parameter for multiple texts and an error callback method. Here's list of all the collection extension methods.

Method Description
nonEmptyList() Returns true if the text is not empty. And returns false if text is empty.
minLengthList() Returns false if the length of text is less than given minimum length.
maxLengthList() Returns false if text length is greater than given length
validEmailList() Returns true if text is a valid email address.
validNumberList() Returns true if the text is any valid number
greaterThanList() Returns false if the text is number less than the given target number
greaterThanOrEqualList() Returns false if the text is number less than or equal to the given target number
lessThanList() Returns false if the text is number greater than the given target number
lessThanOrEqaulList() Returns false if the text is number greater than or equal to the given target number
numberEqualToList() Returns false if the text is a valid number and equal to the given target number
allUperCaseList() Returns false if at least one or more characters are lower case
allLowerCaseList() Returns false if at least one or more characters are upper case
atleastOneUperCaseList() Returns true if at least one or more characters are upper case
atleastOneLowerCaseList() Returns true if at least one or more characters are lower case
atleastOneNumberList() Returns true if at least one or more characters are numbers
startWithNumberList() Returns true if text starts with any number
startWithNonNumberList() Returns false if text starts with any number
noNumbersList() Returns false if the text any number or digit.
onlyNumbersList() Returns false if text contains any alphabetic character
noSpecialCharactersList() Returns true if text contain no special characters
atleastOneSpecialCharactersList() Returns true if text contain at least one special characters
textEqaulToList() Returns false if the text is not equal to the given text
textNotEqualToList() Returns true if the text is not equal to the given text
startsWithList() Returns true if the text starts with the given text
endsWithList() Returns true if the text ends with the given text
containsList() Returns true if the text contains the given text
notContainsList() Returns false if the text contains the given text
creditCardNumberList() Returns true if the text is valid credit card number. This supports Visa, Master Card, American Express, Diners Club, Discover, and JCB.
creditCardNumberWithSpacesList() Returns true if the text is valid credit card number with spaces between 4 characters. This supports Visa, Master Card, American Express, Diners Club, Discover and JCB.
creditCardNumberWithDashesList() Returns true if the text is valid credit card number with dashes between 4 characters. This supports Visa, Master Card, American Express, Diners Club, Discover, and JCB.
validUrlList() Returns true if the text is a valid URL
regexList() Returns true if the text matches passed RegEx pattern.

Built-in Rules

Here is a list of all those rules with their respective methods and collection extensions.

Rule Class Method Names Description
NonEmptyRule nonEmpty() Returns true if the text is not empty. And returns false if text is empty.
MinLengthRule minLength() Returns false if the length of text is less than given minimum length.
MaxLengthRule maxLength() Returns false if text length is greater than given length
EmailRule validEmail() Returns true if text is a valid email address.
ValidNumberRule validNumber() Returns true if the text is any valid number
GreaterThanRule greaterThan() Returns false if the text is number less than the given target number
GreaterThanOrEqualRule greaterThanOrEqual() Returns false if the text is number less than or equal to the given target number
LessThanRule lessThan() Returns false if the text is number greater than the given target number
LessThanOrEqualRule lessThanOrEqaul() Returns false if the text is number greater than or equal to the given target number
NumberEqualToRule numberEqualTo() Returns false if the text is a valid number and equal to the given target number
AllUpercCaseRule allUperCase() Returns false if at least one or more characters are lower case
AllLowerCaseRule allLowerCase() Returns false if at least one or more characters are upper case
AtLeastOneUperCaseRule atleastOneUperCase() Returns true if at least one or more characters are upper case
AtLeastOneLowerCaseRule atleastOneLowerCase() Returns true if at least one or more characters are lower case
AtLeastOneNumberCaseRule atleastOneNumber() Returns true if at least one or more characters are numbers
StartsWithNumberRule startWithNumber() Returns true if text starts with any number
StartsWithNoNumberRule startWithNonNumber() Returns false if text starts with any number
NoNumbersRule noNumbers() Returns false if the text any number or digit.
OnlyNumbersRule onlyNumbers() Returns false if text contains any alphabetic character
NoSpecialCharacterRule noSpecialCharacters() Returns true if text contain no special characters
AtleastOneSpecialCharacterRule atleastOneSpecialCharacters() Returns true if text contain at least one special characters
TextEqualToRule textEqaulTo() Returns false if the text is not equal to the given text
TextNotEqaulToRule textNotEqualTo() Returns true if the text is not equal to the given text
StartsWithRule startsWith() Returns true if the text starts with the given text
EndsWithRule endsWith() Returns true if the text ends with the given text
ContainsRule contains() Returns true if the text contains the given text
NotContainsRule notContains() Returns false if the text contains the given text
CreditCardRule creditCardNumber() Returns true if the text is valid credit card number. This supports Visa, Master Card, American Express, Diners Club, Discover, and JCB.
CreditCardWithSpacesRule creditCardNumberWithSpaces() Returns true if the text is valid credit card number with spaces between 4 characters. This supports Visa, Master Card, American Express, Diners Club, Discover and JCB.
CreditCardWithDashesRule creditCardNumberWithDashes() Returns true if the text is valid credit card number with dashes between 4 characters. This supports Visa, Master Card, American Express, Diners Club, Discover, and JCB.
ValidUrlRule validUrl() Returns true if the text is a valid URL
RegexRule regex() Returns true if the text matches passed RegEx pattern
⚠️ **GitHub.com Fallback** ⚠️