Form Validator Library for Android

Overview

Android-Validator

Form Validator Library for Android

[Flattr this git repo](https://flattr.com/submit/auto?user_id=throrin19&url=https://github.com/throrin19/Android-Validator/&title=Android Validator&language=Java&tags=github&category=software)

Presentation

Form Validator Library for Android is based on Zend_Validator coded in PHP. This library is intended to simplify and streamline the code to validate a form Android. For the moment, the form can just handle the EditText. Other elements will emerge in future versions.

License

Requirement

  • Android 2.2+

Organization

  • demo application demo folder (coming soon)
  • library library project directory
  • others Others Resources directory (icon, sreenshots, ...)
  • library/tests Unit Test Directory (coming soon)

Import in your Project

Graddle Project

Comming Soon

Maven Project

Comming Soon

Testing

In order to execute tests:

gradle localTest

Results are available in app/build/reports/tests/index.html

Use

Form Validator Library is composed of 3 members :

  • Form : Contains all beings validates to treat. This is the Form that manages the display of error messages in the various elements.
  • Validate : Contains all the validators to be treated for a given element.
  • Validator : Can define a validation rule.

Validator

The validator is basic class for this library. It contains specific validation rules. To instanciate validator, you just have to do this (EmailValidator for example):

new EmailValidator(context);

For some validators, functions can change the validation rules. The validator currently contains three basic validation rules:

  • EmailValidator : Ensures that the field does contain a email address. You can also define a regex to check for a particular domain name with the function setDomainName(DomainRegexp). Example for gmail.com domain : setDomainName("gmail\\.com").
  • NotEmptyValidator : Ensures that the field is not empty.
  • UrlValidator : Ensures that the field is a valid url.
  • AlnumValidator : Ensure that the feld has Alnum characters.
  • HexValidator : Ensure that the field has Hex characters.
  • RegExpPattern : Ensure that the field does match setted Pattern.
  • PhoneValidator : Ensure that the field is a valid phone number.
  • RangeValidator : Validates whether the given value is bettween a range of values
  • NumericValidator : Checks whether the field contains only numeric digits
  • IPAddressValidator : Checks whether the field contains a valid IP Address
  • MockValidator : Used by dev as a placeholder while testing validation
  • Custom Validator : You can create your own Validator. To do this, you can just create class extends AbstractValidator :
public class CustomValidator extends AbstractValidator
{
    private int mErrorMessage = R.string.validator_custom; // Your custom error message

    public CustomValidator(Context c) {
        super(c);
    }

    @Override
    public boolean isValid(Object value) {
        // Your validation Test is here.
        // Retour true if it's correct, false if it's incorrect
        return true;
    }

    @Override
    public String getMessage() {
        return mContext.getString(mErrorMessage);
    }
}

Validate

The pure Validate class is a FIFO validator. It's test a list of AbstractValidator for specific EditText. For some special cases, Validate is not enough. This is why there are specific validates. This is why there are two individuals with a Validate operation different from that base :

  • ConfirmValidate : Can check whether a value is identical between the two fields. Can be used to confirm the entry of a password.
  • OrTwoRequiredValidate : If one of the two target fields has a value, then it is valid. Can be used if a user must give his phone or fax.
  • Validate : The base Validate. It creates his validators stack.

Basicly, Validate can only handle a single EditText. If you want to manage several at the same time, see if **ConfirmValidate ** or **OrTwoRequiredValidate ** match your problem. If this is not the case, you may need to create your own Validate. To instantiate a Validate, you just have to do this:

Validate emailField = new Validate(email);

And to add Validator stack, for example to add a required Email field, you have to do this:

emailField.addValidator(new NotEmptyValidator(mContext));
emailField.addValidator(new EmailValidator(mContext));

Form

The Form class is the class teacher of the whole Library. It is this which manages the processing of each Validate, Validator and displays the error on the EditText automatically. The Form class stores a Validate stack and then you just have to run the validation with the validate() function. To instanciate Form and add Validates, you have to do this :

Form mForm = new Form();
mForm.addValidates(emailField);
mForm.addValidates(confirmFields);
mForm.addValidates(urlField);

// ...

// Launch Validation
if(mForm.validate()){
    // success statement
}else{
    // error statement like toast, crouton, ...
}

You can close the error using the form. Can close all errors or just one :

// close one error
mForm.closeError(emailField);
// close all errors
mForm.closeAllErrors()

Contrbute

  • Fork the repo
  • create a branch
    git checkout -b my_branch
    
  • Add your changes
  • Commit your changes:
    git commit -am "Added some awesome stuff"
    
  • Push your branch:
    git push origin my_branch
    
  • Make a pull request to development branch

Changelog

  • 0.1 : Create library
  • 0.2 : Add ConfirmValidate and OrTwoRequiredValidate
  • 0.3 : Extends EmailValidator with setDomainName()
  • 0.4 : Replace Validator by AbstractValidator
  • 0.5 : Fix bug in UrlValidator
  • 1.0 : Add AlnumValidator, HexValidator, RegExpValidator, ValidatorException. Fix Validate class.
  • 1.1 : Go to Android 2.2 for android.util.Patterns. Add PhoneValidator. Edit UrlValidator.
  • 1.5 : Project reorganization, graddle and maven support
  • 1.6.0 : Fix bugs, optimize code, add contributions
  • 1.7.0 : Refactoring/Cleaning, add UnitTest
  • 1.8.0: Optimize code, add new validators
  • 1.9.0 : Add validators, add closeError, closeAllErrors, translate into Korean, set the error message by resId or by specifying a string.
  • 1.10.0 : enable gradle builds of the .aar file, allow use of a custom error drawable, define custom error behavior.

Contributors

Comments
  • Z-index?

    Z-index?

    In the program that I'm coding, I have a sliding layer. When the validator checks and sees that the form isnt complete, it shows the error.

    My problem is that the error pops up over the sliding layer when i slide it from the side but the textview is still under it under it.

    Is there a way i can change the z index of it?

    opened by Exikle 5
  • a (serious?) Bug in form validation

    a (serious?) Bug in form validation

    Hi, I looked at the code for form validation and it looks like the following:

        /**
         * Called to validate our form.
         * If an error is found, it will be displayed in the corresponding field.
         *
         * @return boolean true if the form is valid, otherwise false
         */
        public boolean validate() {
            boolean formValid = true;
            for (AbstractValidate validate : mValidates) {
                // Form is invalid if only one of the validates is false (alternation rule)
                formValid = formValid || validate.isValid();
            }
            return formValid;
        }
    

    since formValid = true from the start, it will always remain true, since x = (true || false) = true and x = (true || true) = true.

    So basically, the form always validates to true. Am I missing something? :(

    I think the OR should be replaced with AND...

    opened by LiorZ 5
  • Potential Memory Leak

    Potential Memory Leak

    Great library for easy form validation in Android, but I have a concern about potential memory leak in AbstractValidator class.

        protected Context mContext;
    
        public AbstractValidator(Context c) {
            mContext = c;
        }
    

    I found out that this Context reference, if instantiated inside a Fragment that setRetainInstance == true, well retain a reference to the first activity passed in constructor.

    AFAIK, according to Android Activity lifecycle, when there's configuration change, e.g when user change display orientation, an Activity will be destroyed and recreated. But a setRetainInstance == true fragment, will not be recreated on a configuration change.

    So, in the end of Activity recreation, my retained fragment still hold a reference to the previously 'destroyed' Activity context, which is certainly a memory leak. CMIIW

    I would like to contribute in this library, planning to have a pull request of my suggested implementation within this week :)

    opened by kemasdimas 3
  • Message display and Translation issue

    Message display and Translation issue

    Hi,

    First of all, thanks for your great jobs.

    It's works great as an Android project. But, I have a problem when I want to use it as a library. Form displays error bubbles (at the right place) but there is no text in bubbles. I try with preset validator (NotEmptyValidator) with en-US, en-GB but still no message.

    There is a screenshot of my app : http://goo.gl/Vu0fj

    I put your string ressources in my main project but always the same problem.

    Did you ever got this issue ? and managed it ?

    opened by matll42 3
  • M.custom error drawable

    M.custom error drawable

    There are 3 things @justincpollard tried to do here:

    1. enable gradle builds of the .aar file;
    2. allow use of a custom error drawable;
    3. define custom error behavior.
    opened by throrin19 2
  • Development

    Development

    Created 3 validators (MockValidator, NumericValidator and IP Validator).

    NumericValidator :

    Checks whether the field contains only numeric digits

    IPAddressValidator :

    Checks whether the field contains a valid IP Address

    MockValidator :

    Used by dev as a placeholder while testing validation

    Can now close the error using the form. Can close all errors or just one.

    public void closeError(TextView sourceTextView) {
        for (AbstractValidate av : mValidates) {
            Validate v = (Validate) av;
            if (v.getSource().equals(sourceTextView))
                v.getSource().setError(null);
        }
    }
    public void closeAllErrors() {
        for (AbstractValidate av : mValidates) {
            Validate v = (Validate) av;
            v.getSource().setError(null);
        }
    }
    

    Fixed up the range validator to match your other validators.

    private static final int DEFAULT_ERROR_MESSAGE_RESOURCE = R.string.validator_range;
    

    Made it so dev can either set the error message by resId or by specifying a string.

    private int mErrorMessageRes;
    
    private String mErrorMessageString;
    
    public AbstractValidator(Context c, int errorMessageRes) {
        mContext = c;
        mErrorMessageRes = errorMessageRes;
        mErrorMessageString = mContext.getString(mErrorMessageRes);
    }
    
    public AbstractValidator(Context c, String errorMessageString) {
        mContext = c;
        mErrorMessageString = errorMessageString;
    }
    
    opened by Exikle 2
  • The type ConfirmValidate must implement the inherited abstract method AbstractValidate.isValid(String)

    The type ConfirmValidate must implement the inherited abstract method AbstractValidate.isValid(String)

    For the classes ConfirmValidate and OrTwoRequiredValidate it looks like the isValid method should take a String object and not Object. This is an issue after changing the two classes to extend the abstract classes.

    opened by huttneab 2
  • Refactoring/Cleaning

    Refactoring/Cleaning

    I made refactoring in order to keep all classes simple (this code should be easier to read). I removed unnecessary code and made shorter methods. I prepared tests to run it with robolectric. Use gradle localTest from library directory to execute all tests (results are available in app/build/reports/tests/index.html).

    opened by piobab 1
  • Validator

    Validator

    Hello, I recently downloaded the library, and using it I found that the validation is sequential, so if I have 6 fields and 5 are erroneous but the latter is correct, then the validation will return true.

    I took the liberty to fix the error I leave the code:

    Class Form:

    public boolean validate(){
        boolean result = true;
        int validator = 0;
        Iterator<AbstractValidate> it = this._validates.iterator();
        while(it.hasNext()){
            AbstractValidate validate = it.next();
            result = validate.isValid();
            if (result == false){
                validator++;
            }
        }
        if (validator > 0){
            result = false;
        }
        return result;
    }
    

    Thank you very much, Andres Bocanumenth

    opened by andresbocanumenth 1
  • Validator in scrollview shows when EditText field is not in view

    Validator in scrollview shows when EditText field is not in view

    Found a potential bug, if you have an EditText in a scrollview at the top of the view and you scroll the page down so that the EditText has scrolled off the view at the top, The validator message scrolls through the action bar covering the action bar

    opened by tyczj 1
  • when EditText show validation error tooltip in pager

    when EditText show validation error tooltip in pager

    hi!

    i have 2 pages. and i can scroll page to left and after that i have see second page

    when i scroll - validation tooltip sticky to the left side of screen

    i have attached img

    a05df728-a33e-11e5-9099-addaca9798a3 a06366ea-a33e-11e5-850f-dc324c933b19 a06604c2-a33e-11e5-86d4-5b8dab95a356

    opened by boomsya 1
  • Failed resolution of: Lcom/throrinstudio/android/example/validator/R$string;

    Failed resolution of: Lcom/throrinstudio/android/example/validator/R$string;

    When I create an instance of any type of Validator, for example, NotEmptyValidator, there always be an error with detailedMessage "Failed resolution of: Lcom/throrinstudio/android/example/validator/R$string;".

    My source code is following: NotEmptyValidator notEmptyValidator = new NotEmptyValidator(fragment.getContext());

    And the cause info of this error is: java.lang.ClassNotFoundException: Didn't find class "com.throrinstudio.android.example.validator.R$string" on path: DexPathList[[zip file "/data/app/com.fourthdimension.gaodingv1android-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]

    opened by XinwenCheng 0
  • Add validation to disabled field

    Add validation to disabled field

    Wanted to know if we can add validation to disabled field. For example an EditText which is filled by output of DatePicker dialog. The DatePicker is enabled on tap of a button.

    opened by sumitsahoo 0
  • Static Error Message in RangeValidator

    Static Error Message in RangeValidator

    Hi,

    In the class "RangeValidator", there is a static class variable called "mErrorMessage". It shouldn't be static as if you have multiple "RangeValidator", it will only keep the last value.

    In my case i had 3 RangeValidator and the same message was displayed three times. Removing "static" modifier fix the issue.

    Actually, i'm also wondering why "getMessage" is overrided in "RangeValidator" while it is not in others validators. :)

    Regards, Clément.

    opened by ClemMahe 0
  • closeAllErrors problem

    closeAllErrors problem

    function closeAllErrors() cant close ConfirmValidate. You'll get exception

    E/AndroidRuntime(27795): java.lang.ClassCastException: >.validator.validate.ConfirmValidate cannot be cast to .validator.Validate

    opened by trungnn307 2
Owner
Benjamin Besse
FullStack Developper @Aquassay, Improviser and guitarist in my spare time. Dev Blogger at Throrin's Studio
Benjamin Besse
Validator - Notify type based validation for input fields.

Validator - Notify type based validation for input fields.

Mustafa Yiğit 57 Dec 8, 2022
UI form validation library for Android

Android Saripaar v2 சரிபார் - sari-paar (Tamil for "to check", "verify" or "validate") Android Saripaar is a simple, feature-rich and powerful rule-ba

Ragunath Jawahar 3.2k Dec 29, 2022
A lightweight, simplified form validation library for Android

A lightweight, simplified form validation library for Android

İbrahim Süren 91 Nov 9, 2022
App to simulate making lemonada juice in form of attractive application

Project: Lemonade App - Starter Code Starter code for the first independent project for Android Basics in Kotlin Introduction This is the starter code

null 0 Oct 28, 2021
Mi-FreeForm - An APP that is activated through Shizuku/Sui and can display most apps in the form of freeform

Mi-FreeForm 简体中文 Mi-FreeForm is an APP that is activated through Shizuku/Sui and

KindBrive 181 Dec 31, 2022
Android library which makes it easy to handle the different obstacles while calling an API (Web Service) in Android App.

API Calling Flow API Calling Flow is a Android library which can help you to simplify handling different conditions while calling an API (Web Service)

Rohit Surwase 19 Nov 9, 2021
Android Utilities Library build in kotlin Provide user 100 of pre defined method to create advanced native android app.

Android Utilities Library build in kotlin Provide user 100 of pre defined method to create advanced native android app.

Shahid Iqbal 4 Nov 29, 2022
A robust native library loader for Android.

ReLinker A robust native library loader for Android. More information can be found in our blog post Min SDK: 9 JavaDoc Overview The Android PackageMan

Keepsafe 2.9k Dec 27, 2022
Joda-Time library with Android specialization

joda-time-android This library is a version of Joda-Time built with Android in mind. Why Joda-Time? Android has built-in date and time handling - why

Daniel Lew 2.6k Dec 9, 2022
UPnP/DLNA library for Java and Android

Cling EOL: This project is no longer actively maintained, code may be outdated. If you are interested in maintaining and developing this project, comm

4th Line 1.6k Jan 4, 2023
:iphone: [Android Library] Get device information in a super easy way.

EasyDeviceInfo Android library to get device information in a super easy way. The library is built for simplicity and approachability. It not only eli

Nishant Srivastava 1.7k Dec 22, 2022
Android library for viewing, editing and sharing in app databases.

DbInspector DbInspector provides a simple way to view the contents of the in-app database for debugging purposes. There is no need to pull the databas

Infinum 924 Jan 4, 2023
Android Market In-app Billing Library

Update In-app Billing v2 API is deprecated and will be shut down in January 2015. This library was developed for v2 a long time ago. If your app is st

Robot Media 533 Nov 25, 2022
An Android library allowing images to exhibit a parallax effect that reacts to the device's tilt

Motion An Android library allowing images to exhibit a parallax effect. By replacing static pictures and backgrounds with a fluid images that reacts t

Nathan VanBenschoten 781 Nov 11, 2022
Android library to easily serialize and cache your objects to disk using key/value pairs.

Deprecated This project is no longer maintained. No new issues or pull requests will be accepted. You can still use the source or fork the project to

Anup Cowkur 667 Dec 22, 2022
Very easy to use wrapper library for Android SharePreferences

Treasure English document Treasure是一个Android平台上基于SharePreferences的偏好存储库,只需要定义接口,无需编写实现,默认支持Serializable和Parcelable。运行时0反射,不仅使用方便而且性能和原生写法几乎无差别。 使用方法 1

星一 507 Nov 12, 2022
Error handling library for Android and Java

ErrorHandler Error handling library for Android and Java Encapsulate error handling logic into objects that adhere to configurable defaults. Then pass

null 237 Dec 29, 2022
Small Android library to help you incorporate MVP, Passive View and Presentation Model patterns in your app

DroidMVP About DroidMVP is a small Android library to help you incorporate the MVP pattern along with Passive View and Presentation Model (yes, those

Andrzej Chmielewski 225 Nov 29, 2022
A simple Android utils library to write any type of data into cache files and read them later.

CacheUtilsLibrary This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize

Wesley Lin 134 Nov 25, 2022