Android form edit text is an extension of EditText that brings data validation facilities to the edittext.

Overview

Android Form EditText

Release

Android form edit text is an extension of EditText that brings data validation facilities to the edittext.

Example App

I built an example app that showcase some of the possibilities of the library.

You'll be able to find the app in the Play Store Here some screenshot of the Example app ( and the library )

Examples list - Email validation

The app source code is located under this repo!

How to include it

This library can be found in maven central repo. If you're using Android studio you can include it by writing the following in the corresponding dependencies block

Gradle:

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}
dependencies {
	// ...
	compile 'com.andreabaccega:android-edittext-validator:1.3.5'
	// ...
}

Maven

        <repositories>
		    <repository>
		        <id>jitpack.io</id>
		        <url>https://jitpack.io</url>
		    </repository>
	    </repositories>
		<dependency>
			<groupId>com.andreabaccega</groupId>
			<artifactId>android-edittext-validator</artifactId>
			<version>${...}</version>
			<type>aar</type>
			<scope>provided</scope>
		</dependency>

Since 1.3.+ the library comes with a new optional dependency: com.android.support.design. This will enable the new TextInputLayout features to be used with the validation engine. Version 1.3.+ depends on com.android.support.design:2.2.0 but if you're not using the support design library you can safely exclude it while including this with gradle by doing so:

dependencies {
    // ..
    implementation 'com.andreabaccega:android-form-edittext:1.3.5'
    // ..
}

How to use

In your xml import an extra namespace on the root of your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:whatever="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:orientation="vertical">
    ....
    <!-- Your actual layout -->
    ....
</LinearLayout>

Note: It's not mandatory to use it on the root element. Also remember to change the xmlns value with your package name

Whenever you need to use the FormEditText just do the following in your xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:whatever="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- Some stuff -->

	<com.andreabaccega.widget.FormEditText
           whatever:testType="alpha"
           android:id="@+id/et_firstname"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           />    

    <!-- Some other stuff -->

</LinearLayout>

As you noticed there is a whatever:test attribute setted to alpha. This let the FormEditText know that the data inside it should be only Alpha characters.

There are several values you can set to the test attribute:

  • regexp: for custom regexp
  • numeric: for an only numeric field
  • alpha: for an alpha only field
  • alphaNumeric: guess what?
  • email: checks that the field is a valid email
  • creditCard: checks that the field contains a valid credit card using Luhn Algorithm
  • phone: checks that the field contains a valid phone number
  • domainName: checks that field contains a valid domain name
  • ipAddress: checks that the field contains a valid ip address
  • webUrl: checks that the field contains a valid url
  • personName: checks if the entered text is a person first or last name.
  • personFullName: checks if the entered value is a complete full name.
  • date: checks that the field is a valid date/datetime format ( if customFormat is set, checks with customFormat )
  • numericRange: checks that the field is a valid value between integers. (minNumber and maxNumber must be set)
  • floatNumericRange: checks that the field is a valid value between integers (but decimal values are allowed). (minNumber and maxNumber must be set)
  • nocheck: It does not check anything except the emptyness of the field.

For most of the test type values this library comes with a couple of default strings. This means that error strings ( english only ) are already available for the following test types: numeric, alpha, alphanumeric

You can customize them using the attributes

  • testErrorString used when the field does not pass the test
  • emptyErrorString used when the field is empty

Example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:whatever="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- Some stuff -->

	<com.andreabaccega.widget.FormEditText
           whatever:testType="alpha"
           whatever:emptyErrorString="@string/your_name_cannot_be_empty"
           whatever:testErrorString="@string/your_name_is_ugly"
           android:id="@+id/et_firstname"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           />    

    <!-- Some other stuff -->

</LinearLayout>

Furthermore you can ask the FormEditText to allow the content to be optional. Just use the emptyAllowed attribute and set it to true. Note: If you don't specify the emptyAllowed attribute the default value is false.

If you want to use regexp as test attribute value you'll need to also use the customRegexp attribute. Take a look in the following example:

Example: (Email check)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:whatever="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <!-- Some stuff -->

	<com.andreabaccega.widget.FormEditText
           whatever:testType="regexp"
           whatever:customRegexp="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$"
           whatever:testErrorString="@string/error_emailnotvalid"
           android:id="@+id/et_email"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:hint="@string/hint_email"
           android:inputType="textEmailAddress"
           />    

    <!-- Some other stuff -->

</LinearLayout>

Note: The library supports the email check natively using the email value as the test attribute.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:whatever="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:orientation="vertical">

    <!-- Some stuff -->

	<com.andreabaccega.widget.FormEditText
           whatever:testType="email"
           android:id="@+id/et_email"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:hint="@string/hint_email"
           android:inputType="textEmailAddress"
           />    

    <!-- Some other stuff -->

</LinearLayout>

In your Java code you'll need to call a method when you want to know if the field validates.

	public void onClickNext(View v) {
		FormEditText[] allFields	= { etFirstname, etLastname, etAddress, etZipcode, etCity };
		
		
		boolean allValid = true;
		for (FormEditText field: allFields) {
			allValid = field.testValidity() && allValid;
		}
		
		if (allValid) {
			// YAY
		} else {
			// EditText are going to appear with an exclamation mark and an explicative message.
		}
	}

Calling testValidity() will cause the EditText to cycle through all the validators and call the isValid method. it will stop when one of them returns false or there are no validators left.

Furthermore testValidity() will also place an exclamation mark on the right of the EditText and will call the setError method.

Add your custom validators

You can add your custom validators runtime through the addValidator method. For example, let's suppouse we want to add a validator that checks that the text input is equal to the string "ciao":

public class CiaoValidator extends Validator {

	public CiaoValidator() {
		super("You should enter 'ciao' here");
	}

	public boolean isValid(EditText et) {
		return TextUtils.equals(et.getText(), "ciao");
	}
	
}

As you can see in the constructor you'll be required to set an Error Message that will be handled ( in this simple scenario ) by the super class. That piece of code will set the error message to: You should enter 'ciao' here.

This means that if the user will not enter "ciao" in the edit text it will get that error message in the popup.

Binary operators

You can use the following binary operators in order to perform checks on the field value:

  • AND: will return true if every enqueued validator returns true
  • OR: will return true if just one enqueued validator returns true
  • NOT: will return the inverse of the passed Validator

With these binary operator validators you'll be able to perform as many different checks as you want. For example, lets say you want a field to be valid either if the user enters his email address or his credit card. Use 'nocheck' in the xml and programmatically do something like this:

  protected void onCreate(Bundle savedInstanceState) {
    // Blabla

    FormEditText fdt = (FormEditText) findViewById(R.id.et);
    fdt.addValidator(
        new OrValidator(
            "This is neither a creditcard or an email", 
            new CreditCardValidator(null), // we specify null as the message string cause the Or validator will use his own message  
            new EmailValidator(null) // same here for null
            )
        );
  }

Author

Contributors

  • ffrog8 - Added the ability to use the library inside the preferences
  • indication - Added japanese translations
  • renclav - Fixed weird bug affecting some 4.2+ devices that prevented the error icon to be shown
Comments
  • Custom colors

    Custom colors

    Hi, I was looking for where can I change the color and I couldn't find the file. Is possible change the red color?. Thanks for the library. It's awesome!

    question 
    opened by iamlordalvarado 6
  • error string internationalisation

    error string internationalisation

    Hi, I need to show error msg for Arabic users which not supported (https://github.com/vekexasia/android-edittext-validator/tree/09a1a466e687e9afb4eef0daf3f179cdae8b967f/library/res) So I use [whatever:emptyErrorString="@string/msg_invalid_data_empty"] into my layout xml file. But it only shows fr msg which is the default language of the phone. Even I force my app to use Arabic language (all other UI are correctly in Arabic). And when I use a Validator from java like this

    MultiValidator tmpValidator = new AndValidator(); tmpValidator.enqueue(new FormAlphaNumericValidator(getResources().getString(R.string.msg_invalid_data_format))); tmpValidator.enqueue(new EmptyValidator(getResources().getString(R.string.msg_invalid_data_empty))); mScannedDocNumber.addValidator(tmpValidator);

    My FormAlphaNumericValidator extends AlphaNumericValidator show correctly the error msg in Arabic. But not the EmptyValidator. Are there a better way to show error msg in Arabic, or should I extends all needed Validators ?

    Thanks,

    opened by mahermeg17 5
  • How to.....Exclude certain words?

    How to.....Exclude certain words?

    I know I'm cheating but hey #YOLO...

    thanks for the lib btw!

    So, If I want to exclude certain words from being entered/accepted in the edittext, what shall i do?

    for example, if a app member types, vase, I want to tell them sorry but that word can't be submitted.

    Thanks!!

    opened by sirvon 5
  • two column of one has filled validation

    two column of one has filled validation

    I just write

    public class HasOneFilledValidator extends Validator { private final EditText otherEditText;

        public HasOneFilledValidator(EditText otherEditText, String errorMessage) {
            super(errorMessage);
            this.otherEditText = otherEditText;
        }
    
        @Override
        public boolean isValid(EditText editText) {
            return (TextUtils.getTrimmedLength(editText.getText()) > 0 || TextUtils.getTrimmedLength(otherEditText.getText())) > 0;
        }
    

    }

    and use AA.addValidator(new HasOneFilledValidator(BB, "test")); but it doen't run isValid... What did I missed?

    opened by AnnShih 4
  • Possible bug in onFocus not always being called when multiple EditText on screen and click on a second

    Possible bug in onFocus not always being called when multiple EditText on screen and click on a second

    First off, I created a fork of the library at: https://github.com/RoundSparrow/android-edittext-validator -- my fork's purpose is to use your work to add a feature I had desired for screen space conservation. A TextView hides each EditText until a user touches the TextView - then they edit appears. You are welcome to absorb this new feature - I added it as a different name - so the library user can have your original FormEditText view. The only real change to your code was to expose a few variables for subclass support...

    In the development and testing of my fork - I found something:

    The onFocus used in this library is not being called in certain touch-transitions away from the EditText field. I assume the validation doesn't always fire due to this bug.

    My fork made it more obvious - because there is a visual change on focus loss... IF YOU WANTED to save time and not bother with my fork - a suggest is to just add one line to set background color on the FormEditText onFocusChanged - and then play around with shifting in and out of the control to see if the color change always appears.

    invalid wontfix 
    opened by RoundSparrow 3
  • Symbols are not resolved when using version 1.0.5 with Gradle

    Symbols are not resolved when using version 1.0.5 with Gradle

    Library symbols are not resolved when I use compile 'com.andreabaccega:android-form-edittext:1.0.5'

    but things are working with no problems when I use version 1.0.4 compile 'com.andreabaccega:android-form-edittext:1.0.4'

    opened by R4md4c 3
  • Consider renaming the library to get more visibility

    Consider renaming the library to get more visibility

    Hi

    I was looking for best practices validating EditText and found your library by chance when was reading the comments on Donn Felker's blog post.

    Only now I noticed that when googling for Android EditText Validation, your library appears on the 6th result. In my opinion this could be improved if you include the word Validation in the library name.

    Great work, cheers!

    opened by Nimrodda 2
  • Added support for Maven

    Added support for Maven

    Added root and module pom.xml files for Maven support. Now allows user to deploy to local repositories or to a managed server (via some additional configuration).

    Updated the .gitignore file to handle some other gen/target ignores that Maven requires, as well as some temporary IntelliJ files for those using alternative IDEs.

    A next step would be to get this deployed to Maven central!

    enhancement 
    opened by dh06IRL 2
  • set optional field

    set optional field

    can you make an option that allows blanks. for example sometimes i have a field and its an optional field , so it can be blank. how to set an optional field that can either have data or not ?

    opened by j2emanue 1
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 1
  •  Failed to resolve: com.andreabaccega:android-edittext-validator:1.3.0

    Failed to resolve: com.andreabaccega:android-edittext-validator:1.3.0

    Hi and thanks for this lib :)

    When I want to put it on my project, I have this error : Failed to resolve: com.andreabaccega:android-edittext-validator:1.3.0 Show in File Show in Project Structure dialog

    This is my Gradle :

    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'
    apply plugin: 'kotlin-kapt'
    apply plugin: 'io.fabric'
    
    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "hey.hey"
            minSdkVersion 19
            targetSdkVersion 27
            versionCode 11
            versionName "2.1.1"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            kapt {
                arguments {
                    arg("room.schemaLocation", "$projectDir/schemas".toString())
                }
            }
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }
        dependencies {
            classpath 'io.fabric.tools:gradle:1.25.2'
        }
    }
    
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
        implementation 'com.android.support:appcompat-v7:27.1.0'
        implementation 'com.android.support:design:27.1.0'
        implementation 'com.android.support.constraint:constraint-layout:1.0.2'
        implementation 'com.android.support:support-v4:27.1.0'
        compile "android.arch.persistence.room:runtime:1.0.0"
        annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
        kapt "android.arch.persistence.room:compiler:1.0.0"
        compile "org.jetbrains.anko:anko-commons:0.10.4"
        compile "org.jetbrains.anko:anko-design:0.10.4"
        compile "com.chibatching.kotpref:kotpref:2.4.0"
        compile "com.chibatching.kotpref:initializer:2.4.0"
        compile('io.socket:socket.io-client:1.0.0') { exclude group: 'org.json', module: 'json' }
        compile 'com.github.anastr:speedviewlib:1.1.7'
        compile 'com.andreabaccega:android-edittext-validator:1.3.0'
        implementation('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') { transitive = true }
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.1'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    }
    
    allprojects {
        repositories {
            maven { url 'https://jitpack.io' }
        }
    }
    
    
    opened by jewom 5
  • Error string/exclamation mark not showing on validation fail

    Error string/exclamation mark not showing on validation fail

    I have the FormEditText wrapped in the TextInputLayout class if that matters.

    Whenever I test the validation, the error or the exclamation mark don't show. I have to manually focus the culprit field to get the error string shown.

    This causes a lot of issues as the user doesn't know what the problem is.

    Here's the xml:

    <android.support.design.widget.TextInputLayout
                    android:id="@+id/til_tradingName"
                    android:layout_width="300dp"
                    android:layout_height="wrap_content"
                    android:hint="@string/trading_name">
    
                    <com.andreabaccega.widget.FormEditText
                        android:id="@+id/tradingName"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:inputType="textCapWords"
                        app:testType="nocheck"/>
    
                </android.support.design.widget.TextInputLayout>
    
    opened by asknask 9
Releases(1.3.4)
Owner
Andrea
I love cooking and writing software.
Andrea
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
AutosizeEditText for Android is an extension of native EditText that offer a smooth auto scale text size.

AutoscaleEditText AutosizeEditText for Android is an extension of native EditText that offer a smooth auto scale text size. Latest Version How to use

Txus Ballesteros 354 Nov 28, 2022
Androids EditText that animates the typed text. EditText is extended to create AnimatedEditText and a PinEntryEditText.

AnimatedEditText for Android This repository contains AnimatedEditText and TextDrawable all of which extend the behaviour of EditText and implement fe

Ali Muzaffar 439 Nov 29, 2022
A single EditText instead of a classical form. Library that implements flavienlaurent's singleinputform

material-singleinputform A single EditText instead of a classical form. This Library is a library implementation of flavienlaurent's "Single input for

Jan Heinrich Reimer 200 Nov 14, 2022
A single EditText instead of a classical form. Library that implements flavienlaurent's singleinputform

material-singleinputform A single EditText instead of a classical form. This Library is a library implementation of flavienlaurent's "Single input for

Jan Heinrich Reimer 200 Nov 14, 2022
Date text field with on the fly validation built with Jetpack Compose.

Date text field with on the fly validation built with Jetpack Compose.

null 15 Nov 16, 2022
Android Custom View for prevent the view behind on-screen keyboard when edit text is focused

Group Focusable Prevent the view behind on-screen keyboard when edit text is focused in Android UI Download Gradle implementation 'com.akexorcist:grou

Akexorcist 8 Jun 22, 2022
An easy approach on how to create your country code picker for the edit text.

Country-Code-Picker Original Article on Dev.to Click below ?? App's Overview In this article, I am going to demonstrate how to create a simple country

Siddharth Singh 5 Mar 10, 2022
LocalizedEditText - Custom edit text that allow only one language

LocalizedEditText Custom edit text that allow only one language Supported languages : Arabic , English Default language : English Examples

Mostafa Gad 1 Nov 28, 2021
An extension of Android's TextView, EditText and Button that let's you use the font of your choice

AnyTextView (deprecated) Note: AnyTextView is no longer being maintained. I recommend replacing AnyTextView with the Calligraphy library instead. Frus

Hans Petter Eide 165 Nov 11, 2022
Android library contain custom realisation of EditText component for masking and formatting input text

Masked-Edittext Masked-Edittext android library EditText widget wrapper add masking and formatting input text functionality. Install Maven <dependency

Evgeny Safronov 600 Nov 29, 2022
Add text masking functionality to Android EditText. It will prevent user from inserting not allowed signs, and format input as well.

MaskFormatter MaskFormatter adds mask functionality to your EditText. It will prevent user from inserting not allowed signs, and format input as well.

Azimo Labs 161 Nov 25, 2022
Simple way to create linked text, such as @username or #hashtag, in Android TextView and EditText

Simple Linkable Text Simple way to create link text, such as @username or #hashtag, in Android TextView and EditText Installation Gradle Add dependenc

Aditya Pradana Sugiarto 76 Nov 29, 2022
A editable text with a constant text/placeholder for Android.

ParkedTextView A EditText with a constant text in the end. How to use <com.goka.parkedtextview.ParkedTextView xmlns:app="http://schemas.android.co

goka 270 Nov 11, 2022
RTL marquee text view android right to left moving text - persian - farsi - arabic - urdo

RTL marquee text view android right to left moving text - persian - farsi - arabic - urdo

mehran elyasi 4 Feb 14, 2022
An Android App example of how to create a custom EditText using DoubleLinkedList Data Structure

DoubleLinkedListEditText Library This is a library to create an EditText based on the Doubly Linked List data structure so that the user can enter cod

Layon Martins 1 Nov 9, 2021
Float Label Edit Texts for Android

Floating Label Edit Text for Android For more info, see this blog post. Salient features Simple and clean library (open up the source to see for yours

null 428 Nov 25, 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
Simple extension for account suggestion and auto completion.

AccountAutoCompleteEditText Just a simple implementation for use of auto complete text view with device account suggestion Usage Just simply put an cu

Keishin Yokomaku 100 Feb 22, 2022