Skip to content

Validation

kevadiya krunal edited this page Mar 28, 2019 · 6 revisions

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 = "krunal.k@gmail.com"
var isValid = myEmailStr.validEmail()  // isValid will be true or false

// Or you can also validate with an error callback method
myEmailStr.validEmail() {
    // 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()        // Checks if edit text is empty or not

// Or with error callback method like this
myEditText.nonEmpty() {
    // 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()
           .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()

Clone this wiki locally