• Stars
    star
    142
  • Rank 258,408 (Top 6 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 6 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easily Validate EditTexts

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

More Repositories

1

TUnit

A modern, fast and flexible .NET testing framework
C#
1,057
star
2

ModularPipelines

Write your pipelines in C# !
C#
276
star
3

ExpandableHintText

A Pretty EditText for Android
Kotlin
184
star
4

RoundImageView

A Round ImageView that works with vectors!
Kotlin
144
star
5

EnumerableAsyncProcessor

Process Multiple Asynchronous Tasks in Various Ways - One at a time / Batched / Rate limited / Concurrently
C#
113
star
6

BDTest

BDTest - A Testing Framework for .NET
C#
75
star
7

A-sync-RedisClient

An asynchronous Redis Client for .NET!
C#
38
star
8

ReadableTimeSpan

A TimeSpan that can be defined as a string in configuration files, and easy to read.
C#
21
star
9

Nupendencies

Automated NuGet Dependency Updater
C#
15
star
10

AllOf

Use Publish/Subscribe type classes without creating Publisher classes
C#
13
star
11

PullRequestScanner

A Github + Azure DevOps Pull Request Scanner that can notify Microsoft Team of current statuses - or plug in your own implementation!
C#
13
star
12

AsyncSemaphore

C#
10
star
13

ILogger.UnitTest.Verifier

Verify ILogger calls more easily.
C#
7
star
14

Selenium.PlaywrightDriver

Use Playwright as if it was a Selenium WebDriver
C#
5
star
15

NotifyValueChanged

A source generated approach, to turn your backing fields into properties that can fire events.
C#
3
star
16

EventMediator

A mediator for eventing - Source Generated publishers from your interfaces - Publish a message and it'll make sure all your subscribers get it
C#
3
star
17

SuspendingTasks

Suspending Tasks for removing callbacks in Android
Kotlin
2
star
18

Resilient-Fallback-Services

C#
2
star
19

MicrosoftDependencyInjection.ServiceInitialization

Initialize your Services on Start-up easily.
C#
2
star
20

Selenium.Extensions

C#
1
star
21

DotNet.HttpExtensions

Useful Extensions revolving around HTTP operations
C#
1
star
22

Selenium.BrowserRequestsWaitingWebDriver

A WebDriver that waits for pending browser requests to complete before continuing
C#
1
star
23

Azure-Service-Bus-Message-Mover

Replay or Move Messages to different buses
C#
1
star
24

ApplicationInsights.TelemetryLogger

An interface alternative TelemetryClient to facilitate testing via dependency inversion
C#
1
star
25

android-contextinjector

Inject Contexts in Fields without cluttering your onCreate !
Kotlin
1
star