Easily Validate EditTexts

Overview

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

You might also like...
A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

Development in this repository is stopped. Future development continues on https://github.com/yigit/android-priority-jobqueue ========================

An Android library that allows you to easily create applications with slide-in menus. You may use it in your Android apps provided that you cite this project and include the license in your app. Thanks!

SlidingMenu (Play Store Demo) SlidingMenu is an Open Source Android library that allows developers to easily create applications with sliding menus li

Easily notify a user with a simple alert, inform them of an optional update, and in dire situations block the user from accessing older versions of the application completely.
Easily notify a user with a simple alert, inform them of an optional update, and in dire situations block the user from accessing older versions of the application completely.

Gandalf In the lifetime of any application there will come a time where you need to drop support for a feature, end of life a product, notify about ma

A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

A library that easily allows you to mask layouts/viewgroups
A library that easily allows you to mask layouts/viewgroups

Maskable Layout Overview ======================= The Maskable Layout is a simple framelayout that allows you to easily mask views and viewgroups. You

Easily add slide to dismiss functionality to an Activity
Easily add slide to dismiss functionality to an Activity

Slidr Easily add slide-to-dismiss functionality to your Activity by calling Slidr.attach(this) in your onCreate(..) method. Usage An example usage: pu

An Android Animation library which easily add itemanimator to RecyclerView items.
An Android Animation library which easily add itemanimator to RecyclerView items.

RecyclerView Animators RecyclerView Animators is an Android library that allows developers to easily create RecyclerView with animations. Please feel

You can easily add awesome animated context menu to your app.
You can easily add awesome animated context menu to your app.

ContextMenu You can easily add awesome animated context menu to your app. Check this project on dribbble Check this project on Behance Usage: For a wo

[] An Android library which allows developers to easily add animations to ListView items
[] An Android library which allows developers to easily add animations to ListView items

DEPRECATED ListViewAnimations is deprecated in favor of new RecyclerView solutions. No new development will be taking place, but the existing versions

You can easily access the top of the screen in Android. Like a iPhone 6 & 6 Plus.
You can easily access the top of the screen in Android. Like a iPhone 6 & 6 Plus.

Reachability on Android Easy access on top. Like a iPhone 6 & 6 Plus. demo apk Usage Add dependencies compile 'com.github.sakebook:Reachability:0.2.0@

EtsyBlur is an Android library that allows developers to easily add a glass-like blur effect implemented in the  Etsy app.
EtsyBlur is an Android library that allows developers to easily add a glass-like blur effect implemented in the Etsy app.

EtsyBlur EtsyBlur is an Android library that allows developers to easily add a glass-like blur effect implemented in the past Etsy app. Try out the sa

[] Easily have blurred and transparent background effect on your Android views.
[] Easily have blurred and transparent background effect on your Android views.

##[DEPRECATED] BlurBehind Easily have blurred and transparent background effect on your Android views. Before API level 14 there was a Window flag cal

Library containing over 2000 material vector icons that can be easily used as Drawable or as a standalone View.
Library containing over 2000 material vector icons that can be easily used as Drawable or as a standalone View.

Material Icon Library A library containing over 2000 material vector icons that can be easily used as Drawable, a standalone View or inside menu resou

Extensible Android mobile voice framework: wakeword, ASR, NLU, and TTS. Easily add voice to any Android app!
Extensible Android mobile voice framework: wakeword, ASR, NLU, and TTS. Easily add voice to any Android app!

Spokestack is an all-in-one solution for mobile voice interfaces on Android. It provides every piece of the speech processing puzzle, including voice

 :sound: [Android Library] Easily generate pure audio tone of any frequency in android
:sound: [Android Library] Easily generate pure audio tone of any frequency in android

Android library to easily generate audio tone in android. Generating pure tone of an specific frequency was never that easy. ZenTone does all the heav

Easily add slide to dismiss functionality to an Activity
Easily add slide to dismiss functionality to an Activity

Slidr Easily add slide-to-dismiss functionality to your Activity by calling Slidr.attach(this) in your onCreate(..) method. Usage An example usage: pu

An Android library to build form and form validations easily.
An Android library to build form and form validations easily.

FormBuilder An Android library to build form and form validations easily. Example COMING SOON Requirements Android 4.3+ Installation Add edit your bui

Under the Hood is a flexible and powerful Android debug view library. It uses a modular template system that can be easily extended to your needs, although coming with many useful elements built-in.
Under the Hood is a flexible and powerful Android debug view library. It uses a modular template system that can be easily extended to your needs, although coming with many useful elements built-in.

Under the Hood - Android App Debug View Library Under the Hood is a flexible and powerful Android debug view library. It uses a modular template syste

A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

This Project is Deprecated! Thanks to everybody who've used Android Priority JobQueue. It was designed in a world where there was no JobScheduler, RxJ

Releases(1.0.8)
Owner
Tom Longhurst
Developer / Photographer
Tom Longhurst
Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Provides easy means to validate with dependencies.

android-formidable-validation Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Pr

Linden 147 Nov 20, 2022
A tool that facilitates working with Spans on TextViews or any extension of them (EditTexts, Buttons...).

AwesomeText Working with Spans is ugly and difficult to manage, it's like working with a goblin of Moria. Don't understand the Spans? With AwesomeText

José Manuel Pereira García 674 Nov 27, 2022
💰 A library to dynamically format your EditTexts to take currency inputs

CurrencyEditText A library to dynamically format your EditTexts to take currency inputs. Gradle Dependency Add the dependency to your app's build.grad

Cotta & Cush Limited 115 Dec 28, 2022
Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Provides easy means to validate with dependencies.

android-formidable-validation Form validation and feedback library for Android. Provides .setText for more than just TextView and EditText widgets. Pr

Linden 147 Nov 20, 2022
A tool to validate text inside TextInputLayout

Download dependencies { implementation 'com.github.anderscheow:validator:2.2.1' } Usage Available rules LengthRule MaxRule MinRule NotEmptyRule NotN

Anders Cheow 129 Nov 25, 2022
Extremely useful library to validate EditText inputs whether by using just the validator for your custom view or using library's extremely resizable & customisable dialog

Extremely useful library for validating EditText inputs whether by using just the validator (OtpinVerification) for your custom view or using library's extremely resizable & customisable dialog (OtpinDialogCreator)

Ehma Ugbogo 17 Oct 25, 2022
Android UI component to validate passwords.

PasswordValidationView Android UI component that validates passwords. All design credits goes to Piotr Sliwa And inspired by this design Demo Setup Ad

Kojo Fosu Bempa Edue 81 Nov 29, 2022
Java/Kotlin lightweight implementation of RFC-6238 and RFC-4226 to generate and validate time-based one-time passwords (TOTP).

1time Java/Kotlin lightweight implementation of RFC-6238 and RFC-4226 to generate and validate time-based one-time passwords (TOTP). Maven / gradle de

Atlassian Labs 31 Dec 21, 2022
View Navigator is a tool that allows you to inspect and validate all the views of a screen individually.

?? View Navigator View Navigator is a tool that allows you to inspect and validate all the views of a screen individually, highlighting the margins an

Marcelo Alban 5 Nov 29, 2022
AnyChart Android Chart is an amazing data visualization library for easily creating interactive charts in Android apps. It runs on API 19+ (Android 4.4) and features dozens of built-in chart types.

AnyChart for Android AnyChart Android Charts is an amazing data visualization library for easily creating interactive charts in Android apps. It runs

AnyChart 2k Jan 4, 2023