A tool to validate text inside TextInputLayout

Overview

Android Arsenal Build Status codecov

Download

dependencies {
  implementation 'com.github.anderscheow:validator:2.2.1'
}

Usage

Available rules

  • LengthRule
  • MaxRule
  • MinRule
  • NotEmptyRule
  • NotNullRule
  • RegexRule
  • AlphabetRule
  • AlphanumericRule
  • DigitsRule
  • EmailRule
  • PasswordRule
  • FutureRule
  • PastRule
  • CreditCardRule
  • ContainRule
  • NotContainRule
  • EqualRule
  • NotEqualRule
  • NotBlankRule
  • AllUpperCaseRule
  • AllLowerCaseRule
  • EndsWithRule
  • StartsWithRule
  • SymbolRule

Additional predefined rules to use in Validation or Condition

  • contain
  • notContain
  • notEqualTo
  • withinRange
  • minimumLength
  • maximumLength
  • email
  • alphanumericOnly
  • alphabetOnly
  • digitsOnly
  • symbolsOnly
  • allUppercase
  • allLowercase
  • startsWith
  • endsWith
  • withCreditCard
  • withPassword
  • notNull
  • notEmpty
  • notBlank
  • regex
  • future
  • past
  • matchAtLeastOneRule (Only for Validation)
  • matchAllRules (Only for Validation)

You can create your own Predefined Rules

// For Validation
fun Validation.customPredefinedRule(keyword: String, ignoreCase: Boolean = false): Validation {
    baseRules.add(ContainRule(keyword, ignoreCase))
    return this
}
 
// For Condition
fun Condition.customPredefinedRule(keyword: String, ignoreCase: Boolean = false): Condition {
    baseRules.add(ContainRule(keyword, ignoreCase))
    return this
}

Beside from using the provided Rules, you can create your own Rule by extending BaseRule (Create as many as you want)

class CustomRule : BaseRule {
 
    override fun validate(value: String?): Boolean {
        if (value == null) {
            throw NullPointerException()
        }
        return value == "ABC"
    }
 
    // You can use this to return error message
    override fun getErrorMessage(): String {
        return "Value doesn't match 'ABC'"
    }
 
    // or use this to return error message as StringRes
    override fun getErrorRes(): Int {
        return R.string.error_not_match
    }
}

Add it to your Activity class

// Username
// Input: [email protected]
val usernameInput = findViewById(R.id.layout_username)
val usernameValidation = Validation(usernameInput)
                .addRule(
                    // You can also override the default error message
                    NotEmptyRule(R.string.error_not_empty)
                     
                    // Use either errorRes() or errorMessage()
                    // Note: errorRes() has higher priority
                    NotEmptyRule("Value is empty")
                )
                .addRule(CustomRule())
 
// Password
// Input: 12345abc
val passwordInput = findViewById(R.id.layout_password)
val passwordValidation = Validation(passwordInput)
                .addRule(NotEmptyRule())
                .withPassword(PasswordRegex.ALPHA_NUMERIC)
                .minimumLength(8)

Condition

// And Condition
val usernameWithConditionValidation = Validation(usernameInput)
                .add(And().add(EmailRule()))
 
// Or Condition
val usernameWithConditionValidation = Validation(usernameInput)
                .add(Or().add(MinRule(5)).add(MaxRule(10)))
 
// Both by using Predefined Rules
val usernameWithConditionValidation = new Validation(usernameInput)
                .matchAllRules(listOf(EmailRule()))
                .matchAtLeastOneRule(listOf(MinRule(5), MaxRule(10)))

Mode

Validator.with(applicationContext)
            /* Set your mode here, by default is CONTINUOUS */
            .setMode(Mode.CONTINUOUS));
Single Continuous

Validate the input field

// Order of the values on the success callback follow the sequence of your Validation object
Validator.with(applicationContext)
            .setMode(Mode.CONTINUOUS)
            .setListener(object : Validator.OnValidateListener {
                    override fun onValidateSuccess(values: List<String>) {
                        Log.d("MainActivity", values.toTypedArray().contentToString())
                        Toast.makeText(applicationContext, "Validate successfully", Toast.LENGTH_LONG).show()
                    }

                    override fun onValidateFailed(errors: List<String>) {
                        Log.e("MainActivity", errors.toTypedArray().contentToString())
                    }
                })
            .validate(usernameValidation, passwordValidation)

Changelog

2.2.1

  • Added Validation.notNull, Validation.notEmpty, Validation.notBlank, Validation.regex, Validation.past and Validation.future
  • Can use TextInputLayout.validate or TextInputLayout.add instead of Validation(TextInputLayout) in Kotlin

2.2.0

  • Added AllUpperCaseRule, AllLowerCaseRule, StartsWithRule, EndsWithRule and SymbolRule
  • Changed validate(Any?) to validate(String?)

2.1.2

  • Added NotEmptyRule
  • Added error messages into Validator.OnValidateListener.onValidateFailed()

2.1.0

  • Updated Gradle and Kotlin version
  • Changed Android Support artifacts to AndroidX
  • Removed some install dependencies from README

2.1.0

  • Updated Gradle and Kotlin version
  • Changed Android Support artifacts to AndroidX
  • Removed some install dependencies from README

2.0.1

  • Updated to support Android SDK 28
  • Converted Android Support to AndroidX

1.3.1

  • Addressed some algorithm issues
  • Added more test cases

1.3.0

  • Removed Validation.and() and Validation.or() by encouraging user to use Condition
  • Removed listener parameter from Validator.validate() and required to assigned manually using Validator.setListener()
  • Added some predefined rules in Validation and Condition to simplify procedure on adding rules

1.2.2

  • Added Dokka to show Kotlin sources

1.2.1

  • Removed generic type from BaseRule as there's a limitation

  • validate() only accept "Any?" as parameter

1.2.0

  • For version lower than 1.2.0, upgrading to latest version may broke your code. Use it at your risk

  • Updated to Kotlin

  • Validation does support for Object parameter instead of just TextInputLayout (Refer to example below)

  • Set TextInputLayout.setErrorEnabled(false) on every Validate method called

1.1.5

  • Removed unwanted log

1.1.4

  • Fixed an issue where validate will success if last validation pass the rules in Mode.CONTINUOUS

  • RegexRule now is open class rather than abstract class

1.1.3

  • Input can be any object, previously restrict to String (Along with proper validation with different object)

  • Added more test cases to validate input

1.1.2

  • Updated ALPHA_NUMERIC_SYMBOLS regex on PasswordRule

1.1.1

  • Fixed bug where overloading the constructor with errorMessage or errorRes does not override the default value

1.1.0

  • Added ability to add conditions (And or Or)

  • Added mode of validation (Single or Continuous)

  • Added ability to override errorRes or errorMessage in constructor without overriding the methods

1.0.4

  • Added more rules, please check at 'Available Rules'

1.0.3

  • Fixed LengthRule wrong validation on maxValue

1.0.2

  • Added success and failed callback instead of just success callback

  • Success callback return list of EditText values (Order by sequence of Validation object(s))

1.0.1

  • Added some common rules (LengthRule, MinRule, MaxRule, RegexRule etc.)

  • Able to use String as error message

1.0.0

  • Introduce Validator library

Testing

I have added unit testing for Rules and Conditions, soon will provide test code on Validation and Validator, please check it out under Test code

Contributions

Any contribution is more than welcome! You can contribute through pull requests and issues on GitHub.

License

Validator is released under the MIT License

Comments
  • NotEqualTo Base Rule not Working Correctly

    NotEqualTo Base Rule not Working Correctly

    The NotEqualRuleand EqualRule are not working for dynamic texts. For Example

    Validation passwordConfirmValidation = new Validation(confirmPasswordWrapper).add(new NotEqualRule(password.getText(),"Passwords Are not equal"));
    

    This Doesn't Work. and If you remove the Custom error, It says: The value is not equal to '' as error text

    opened by LaserStony 11
  • Hi , About the Validator.kt

    Hi , About the Validator.kt

    Line 51 code: val value = (editText?.text ?: validation.textInput).toString() It should be changed to, val value = (editText?.text ?: validation.textInput?.text).toString()

    opened by phoebewow 5
  • is this Library this only useful on android?

    is this Library this only useful on android?

    is this Library this only useful on android?

    I worked on a similar project and just want to know if I can stop my work if this is compatible with Kotlin JVM :D

    opened by mustii82 3
  • Password confirmation validation rule proposal

    Password confirmation validation rule proposal

    This is a suggestion to add PasswordMatchRule for "confirm password" behaviours, along with withPasswordConfirmation(...) extensions.

    Code follows:

    class PasswordMatchRule(private val passwordInput: EditText, errorRes: Int) : BaseRule(errorRes) {
    
        override fun validate(value: String?): Boolean {
            return passwordInput.text.toString() == value
        }
    
    }
    
    opened by Kaned1as 2
  • Simple checkbox validation

    Simple checkbox validation

    CheckBox class also has "setError(...)/getError(...)" calls which set error drawable, albeit without text.

    We could extend Validation class to support them as many input forms also have checkboxes, e.g., "I accept EULA", "I confirm I'm above 18" or "I agree to sell my kidney".

    What do you think?

    opened by Kaned1as 1
Owner
Anders Cheow
Anders Cheow
Multiplaform kotlin library for calculating text differences. Based on java-diff-utils, supports JVM, JS and native targets.

kotlin-multiplatform-diff This is a port of java-diff-utils to kotlin with multiplatform support. All credit for the implementation goes to original a

Peter Trifanov 51 Jan 3, 2023
Matches incoming and/or outgoing text messages against set rules and sends them over to webhook.

Textmatic If you ever wanted a tool to simply push the SMS (or text messages) from your phone to somewhere remote, this is it. This app matches all in

Float 2 Jan 7, 2022
LearningRegex - Parse links from text via RegEx

Parse links from text via RegEx Supported types: Hashtags Urls emails Using in p

Boris 0 Feb 16, 2022
Same as the Outlined text fields presented on the Material Design page but with some dynamic changes. 📝 🎉

README SSCustomEditTextOutlineBorder Getting Started SSCustomEditTextOutLineBorder is a small kotlin library for android to support outlined (stroked)

Simform Solutions 194 Dec 30, 2022
Draw Text on any Pixelflut Canvas.

PixelJet A PixelFlut tool which paints the given text to the canvas. It connects to a running Pixelflut server, renders the text with a given font and

Markus Pöschl 0 Apr 30, 2022
An easy-to-use, cross-platform measurement tool that pulls data out of CD pipelines and analysis the four key metrics for you.

Maintained by SEA team, ThoughtWorks Inc. Read this in other languages: English, 简体中文 Table of Contents About the Project Usage How to Compute Contrib

Thoughtworks 277 Jan 7, 2023
recompose is a tool for converting Android layouts in XML to Kotlin code using Jetpack Compose.

recompose is a tool for converting Android layouts in XML to Kotlin code using Jetpack Compose.

Sebastian Kaspari 565 Jan 2, 2023
An intelligent diff tool for the output of Gradle's dependencies task

Dependency Tree Diff An intelligent diff tool for the output of Gradle's dependencies task which always shows the path to the root dependency. +--- c

Jake Wharton 693 Dec 26, 2022
Utility tool to make you a computer ninja.

Cmd Window Never spend 6 minutes doing something by hand when you can spend 6 hours failing to automate it - Zhuowej Zhang What is this about? This to

Marcin Radoszewski 3 Feb 1, 2022
BinGait is a tool to disassemble and view java class files, developed by BinClub.

BinGait Tool to diassemble java class files created by x4e. Usage To run BinGait, run java -jar target/bingait-shadow.jar and BinGait will launch. If

null 18 Jul 7, 2022
A command line tool for NFT stuff

MartaKli is a command line tool to help you generate your NFT pfp project. Current features: Generate batch of images using different layers and corre

Martabak Cult 2 Oct 4, 2022
KDoctor - A command-line tool that helps to set up the environment for Kotlin Multiplatform Mobile app development

KDoctor is a command-line tool that helps to set up the environment for Kotlin Multiplatform Mobile app development.

Kotlin 331 Dec 29, 2022
Tool to look for several security related Android application vulnerabilities

Quick Android Review Kit This tool is designed to look for several security related Android application vulnerabilities, either in source code or pack

LinkedIn 2.9k Jan 2, 2023
A simple customised version of the TextInputLayout from the Android Design Support Library ⌨️

Buffer Text Input Layout (Coming to maven central soon!) This is a simple customisation of the TextInputLayout found in the Design Support Library. Wh

Buffer 988 Nov 24, 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
A library that gives full control over text related technologies such as bidirectional algorithm, open type shaping, text typesetting and text rendering

Tehreer-Android Tehreer is a library which gives full control over following text related technologies. Bidirectional Algorithm OpenType Shaping Engin

Tehreer 61 Dec 15, 2022
Speech-Text Converter is a simple task that enable the user to convert the speech to text or convert text to speech (by Mic)

Speech-Text Converter About Speech-Text Converter is a simple task that enable the user to convert the speech to text or convert text to speech (by Mi

Kareem Saeed 1 Oct 21, 2021
An all-in-one Jetpack Compose component to handle text styling inside TextFields

An all-in-one Jetpack Compose component to handle text styling inside TextFields

Paweł Chochura 26 Dec 14, 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
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