Giter Site home page Giter Site logo

android-validator's Introduction

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

android-validator's People

Contributors

2bard avatar amondnet avatar andreamaglie avatar atermenji avatar bitdeli-chef avatar dbachelder avatar jitpack-io avatar leandros avatar liorz avatar piobab avatar rogerg9999 avatar sys1yagi avatar throrin19 avatar tsoliver avatar veelck avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-validator's Issues

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.

Other validatable objects?

....the form can just handle the EditText.

Just wondering what other objects did you want to validate. I wanted to try coding it

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]]

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.

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

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...

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 :)

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

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?

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 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.