Coder Social home page Coder Social logo

android-edittext-validations's Introduction

Android EditText Validations

Easily Validate EditTexts

Codacy Badge Android Weekly

This library is best used with Kotlin, and is to help reduce boilerplate code when writing validation rules for EditText fields.

To install:

Add Jitpack to your repositories in your build.gradle file

allprojects {
    repositories {
      // ...
      maven { url 'https://jitpack.io' }
    }
}

Add the below to your dependencies, again in your gradle.build file

implementation 'com.github.thomhurst:Android-EditText-Validations:{version}'

Usage

Using a reference to your edit text:

val editText = EditText(applicationContext)

You can define failures in an apply block:

editText.apply {
    failWithMessageIf(errorMessage = "Text must not be blank", condition = { it.toString().isBlank() })
    failIf { it.toString().length > 30 }
    failWithMessageIf(errorMessage = "Text must be less than 30 characters", condition = { !it.toString().isDigitsOnly() })
}

Or you can chain failures together:

editText
    .failWithMessageIf(errorMessage = "Text must not be blank", condition = { it.toString().isBlank() })
    .failIf { !it.toString().isDigitsOnly() }
    .failWithMessageIf(errorMessage = "Text must be less than 30 characters", condition = { it.toString().length > 30 })

As you can see, you can specify your own rules as above, or you can use some of the preset rules by using an enum:

editText
    .failWithMessageIf(errorMessage = "Must not be blank", editTextCondition = EditTextCondition.IS_BLANK_OR_EMPTY)

The enums available are:

    IS_EMPTY,
    IS_BLANK_OR_EMPTY,
    NOT_VALID_EMAIL,
    NOT_LETTERS_ONLY,
    NOT_NUMBERS_ONLY,
    NOT_LETTERS_OR_NUMBERS_ONLY,
    CONTAINS_SPECIAL_CHARACTERS

Calling EditText.validationPassed will return you a boolean true or false

if (editText.validationPassed()) {
    // This will return either true or false based on the failures defined
}

Or you can call EditText.validate and define code to be executed in a callback; onValidationPassed or onValidationFailed

editText
    .validate(
        onValidationPassed = {
            // Code to execute if all the validation has passed
        },
        onValidationFailed = {
            // Code to execute if any validation has failed.
        }
    )

You can also call EditText.validateAndShowError which will execute the same as validate, however it will also apply an error with a message (if you've provided one) to your EditText.

onValidationFailed will return a list of error messages that failed. You can then display these however you want. Toast, Snackbar or EditText error, etc.

onValidationFailed = { errorMessages ->
    // Any failed validation messages are returned here so we can set error messages however we like
    errorMessages.firstOrNull()?.let { firstErrorMessage ->
        // Show Error Toast
        Toast.makeText(applicationContext, firstErrorMessage, Toast.LENGTH_LONG).show()

        // Show error snackbar
        Snackbar.make(findViewById(android.R.id.content), firstErrorMessage, Snackbar.LENGTH_INDEFINITE).show()

        // Show edit text error
        editText.error = firstErrorMessage
    }
}

Using EditText.failWithMessageRealTimeIf will cause an EditText error to be displayed in real time. So, if while they're typing, they enter data that breaks your validation, this will be flagged instantly.

You can dynamically get the failed error messages at any time using EditText.failedValidationMessages which will return a list of error messages.

Collections

To validate multiple text fields at once, you have a few ways:

if(editText1.validationPassed() && editText2.validationPassed() && editText3.validationPassed()) {
            ...
        }
// Varargs of EditTexts using EditTextValidation helper class
EditTextValidation.validationPassed(editText1, editText2, editText3) // Boolean - True or False

// Collection of EditTexts using EditTextValidation helper class
EditTextValidation.validationPassed(listOf(editText1, editText2, editText3)) // Boolean - True or False
// Varargs of EditTexts using EditTextValidation helper class
EditTextValidation.validate(editText1, editText2, editText3,
            onValidationPassed = {
                ...
            },
            onValidationFailed = { failedEditTexts ->
                ...
            })

// Collection of EditTexts using EditTextValidation helper class
EditTextValidation.validate(listOf(editText1, editText2, editText3),
            onValidationPassed = {
                ...
            },
            onValidationFailed = { failedEditTexts ->
                ...
            })
// Set of EditTexts using Collection Extension Method
setOf(editText1, editText2, editText3).validationPassed() // Boolean - True or False

// List of EditTexts using Collection Extension Method
listOf(editText1, editText2, editText3).validationPassed() // Boolean - True or False
// Set of EditTexts using Collection Extension Method
setOf(editText1, editText2, editText3).validate(
            onValidationPassed = {
                ...
            },
            onValidationFailed = { failedEditTexts ->
                ...
            })
            
// List of EditTexts using Collection Extension Method
listOf(editText1, editText2, editText3).validate(
            onValidationPassed = {
                ...
            },
            onValidationFailed = { failedEditTexts ->
                ...
            })

And to easily grab error messages within these collection callbacks:

onValidationFailed = { failedEditTexts ->
                failedEditTexts.forEach { failedEditText ->
                    failedEditText.failedValidationMessages.forEach { failedValidationMessage ->
                        failedEditText.error = failedValidationMessage
                    }
                }
            }

If you enjoy, please buy me a coffee :)

Buy Me A Coffee

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.