Giter Club home page Giter Club logo

awesomevalidation's Introduction

API Maven Central JitPack Build & Test Travis CI Status CircleCI Status Codacy Badge Android Arsenal Android Weekly Trusted By Many Apps AppBrain

AwesomeValidation

Introduction

Implement validation for Android within only 3 steps. Developers should focus on their awesome code, and let the library do the boilerplate. And what's more, this could help keep your layout file clean.

Steps

  1. Declare validation style;
  2. Add validations;
  3. Set a point when to trigger validation.

Sample code

// Step 1: designate a style
AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
// or
AwesomeValidation mAwesomeValidation = new AwesomeValidation(COLORATION);
mAwesomeValidation.setColor(Color.YELLOW);  // optional, default color is RED if not set
// or
AwesomeValidation mAwesomeValidation = new AwesomeValidation(UNDERLABEL);
mAwesomeValidation.setContext(this);  // mandatory for UNDERLABEL style
// setUnderlabelColor is optional for UNDERLABEL style, by default it's holo_red_light
mAwesomeValidation.setUnderlabelColorByResource(android.R.color.holo_orange_light); // optional for UNDERLABEL style
mAwesomeValidation.setUnderlabelColor(ContextCompat.getColor(this, android.R.color.holo_orange_dark)); // optional for UNDERLABEL style
// or
AwesomeValidation mAwesomeValidation = new AwesomeValidation(TEXT_INPUT_LAYOUT);
mAwesomeValidation.setTextInputLayoutErrorTextAppearance(R.style.TextInputLayoutErrorStyle); // optional, default color is holo_red_light if not set
// by default, it automatically sets focus to the first failed input field after validation is triggered
// you can disable this behavior by
AwesomeValidation.disableAutoFocusOnFirstFailure();

// Step 2: add validations
// support regex string, java.util.regex.Pattern and Guava#Range
// you can pass resource or string
mAwesomeValidation.addValidation(activity, R.id.edt_name, "[a-zA-Z\\s]+", R.string.err_name);
mAwesomeValidation.addValidation(activity, R.id.edt_tel, RegexTemplate.TELEPHONE, R.string.err_tel);
mAwesomeValidation.addValidation(activity, R.id.edt_email, android.util.Patterns.EMAIL_ADDRESS, R.string.err_email);
mAwesomeValidation.addValidation(activity, R.id.edt_year, Range.closed(1900, Calendar.getInstance().get(Calendar.YEAR)), R.string.err_year);
mAwesomeValidation.addValidation(activity, R.id.edt_height, Range.closed(0.0f, 2.72f), R.string.err_height);
// or
mAwesomeValidation.addValidation(editText, "regex", "Error info");

// to validate TextInputLayout, pass the TextInputLayout, not the embedded EditText
AwesomeValidation mAwesomeValidation = new AwesomeValidation(TEXT_INPUT_LAYOUT);
mAwesomeValidation.addValidation(activity, R.id.til_email, Patterns.EMAIL_ADDRESS, R.string.err_email);

// to validate the confirmation of another field
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!@#\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{8,}";
mAwesomeValidation.addValidation(activity, R.id.edt_password, regexPassword, R.string.err_password);
// to validate a confirmation field (don't validate any rule other than confirmation on confirmation field)
mAwesomeValidation.addValidation(activity, R.id.edt_password_confirmation, R.id.edt_password, R.string.err_password_confirmation);

// to validate with a simple custom validator function
mAwesomeValidation.addValidation(activity, R.id.edt_birthday, new SimpleCustomValidation() {
    @Override
    public boolean compare(String input) {
        // check if the age is >= 18
        try {
            Calendar calendarBirthday = Calendar.getInstance();
            Calendar calendarToday = Calendar.getInstance();
            calendarBirthday.setTime(new SimpleDateFormat("dd/MM/yyyy", Locale.US).parse(input));
            int yearOfToday = calendarToday.get(Calendar.YEAR);
            int yearOfBirthday = calendarBirthday.get(Calendar.YEAR);
            if (yearOfToday - yearOfBirthday > 18) {
                return true;
            } else if (yearOfToday - yearOfBirthday == 18) {
                int monthOfToday = calendarToday.get(Calendar.MONTH);
                int monthOfBirthday = calendarBirthday.get(Calendar.MONTH);
                if (monthOfToday > monthOfBirthday) {
                    return true;
                } else if (monthOfToday == monthOfBirthday) {
                    if (calendarToday.get(Calendar.DAY_OF_MONTH) >= calendarBirthday.get(Calendar.DAY_OF_MONTH)) {
                        return true;
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }
}, R.string.err_birth);

// to validate with your own custom validator function, warn and clear the warning with your way
mAwesomeValidation.addValidation(activity, R.id.spinner_tech_stacks, new CustomValidation() {
    @Override
    public boolean compare(ValidationHolder validationHolder) {
        if (((Spinner) validationHolder.getView()).getSelectedItem().toString().equals("< Please select one >")) {
            return false;
        } else {
            return true;
        }
    }
}, new CustomValidationCallback() {
    @Override
    public void execute(ValidationHolder validationHolder) {
        TextView textViewError = (TextView) ((Spinner) validationHolder.getView()).getSelectedView();
        textViewError.setError(validationHolder.getErrMsg());
        textViewError.setTextColor(Color.RED);
    }
}, new CustomErrorReset() {
    @Override
    public void reset(ValidationHolder validationHolder) {
        TextView textViewError = (TextView) ((Spinner) validationHolder.getView()).getSelectedView();
        textViewError.setError(null);
        textViewError.setTextColor(Color.BLACK);
    }
}, R.string.err_tech_stacks);

// Step 3: set a trigger
findViewById(R.id.btn_done).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mAwesomeValidation.validate();
    }
});

// Optional: remove validation failure information
findViewById(R.id.btn_clr).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mAwesomeValidation.clear();
    }
});

Attention

  • It works perfectly with Fragment, but please pay attention to Fragment's lifecycle. You should set the validate() inside Fragment's onActivityCreated instead of onCreateView or any other early stage.

  • UNDERLABEL validation style doesn't support ConstraintLayout at the moment, please use other validation styles. There is an open issue here.

Import as dependency

For Gradle it's easy - just add below to your module's build.gradle (it's available on Maven Central):

dependencies {
    implementation 'com.basgeekball:awesome-validation:4.3'
}

Alternatively, it's also available on JitPack:

  • Add it in your root build.gradle at the end of repositories:
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}
  • Add the dependency
dependencies {
    implementation 'com.github.thyrlian:AwesomeValidation:v4.3'
    // you can also use the short commit hash to get a specific version
    // implementation 'com.github.thyrlian:AwesomeValidation:GIT_COMMIT_HASH'
}

Screenshots

Release guide

  • Update version number in build.gradle, gradle.properties and README
  • Create new git tag: v*.*
  • Make sure a local.properties file which holds the necessary credentials is present under the library directory
  • Run ./gradlew clean build && ./gradlew :library:publishReleasePublicationToSonatypeRepository to generate release file and upload it to Nexus Repository

Stargazers over time

Stargazers over time

License

Copyright (c) 2014-2021 Jing Li. See the LICENSE file for license rights and limitations (MIT).

awesomevalidation's People

Contributors

etryp avatar hongdongni avatar ilya-gh avatar mahboubii avatar nisrulz avatar temirnurdin avatar thyrlian avatar waffle-iron 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  avatar

awesomevalidation's Issues

Kotlin Samples

Sample usage on how to use this with Kotlin is missing!

Add option to clear individual error on text changed

I'm using ValidationStyle.UNDERLABEL as my validation style.

Now as far as I could explore , I could find a method to clear error from all the form fields:
mAwesomeValidation.clear();

However, I am not able to remove error from a single EditText. My requirement is, when a user starts typing in an EditText field, it should remove the under label error. I've tried using setError(null) on the EditText but it isn't working. Is there any way to do this?

Required validation on ImageView

I have used the library to validate Text-views in my android application.How to add Required validation for image view?(i.e if the image is not selected before submitting it should show error like profile image is required?).Is it possible to achieve by using this library?

It can not work with "support.design.widget.TextInputLayout"

if EditText surround with TextInputLayout,like this ->

<android.support.design.widget.TextInputLayout
                android:id="@+id/til_guangai_date"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <EditText
                    android:id="@+id/et_guangai_date"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10" />
            </android.support.design.widget.TextInputLayout>

This will trigger an exception ,Exception details:

We already have an EditText, can only have one

Focus runs away ... :(

https://gyazo.com/c41f51d2253ea5dbef0dcdb0d290c252

        val validation = AwesomeValidation(ValidationStyle.TEXT_INPUT_LAYOUT)
        validation.addValidation(
                address_edittext_layout,
                Patterns.EMAIL_ADDRESS,
                getString(R.string.incorrect_input_type)
        )
        val passwordRegex = "(?=.*[a-zA-Z])(?=.*[\\d]).{8,}"
        validation.addValidation(
                password_edittext_layout,
                passwordRegex,
                getString(R.string.incorrect_password)
        )

validation.validate() is fired on TextWatcher#afterTextChanged
Is there a solution?

Error adding validation

Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 24: TypedValue{t=0x3/d=0x13a "res/color/secondary_text_material_light.xml" a=1 r=0x106011a}

on this line
if (awesomeValidation.validate()) {}

How to simply say that a field is required?

For most of my textedit fields, the only constraint is that they cannot be blank. Is there a way to simply specify that constraint, without going through an overkill regex? Because I didn't find any example of that in the sample app, or in the README.

Remove Guava Dependency

Hi:

Guava dependency takes a lot of space when releasing a build. So having the Dependency is such a problem with the usage on an Android App.

It should be removed, so at least up to 4Mb of space can be saved up.

Don't validate invisible or gone fields

When a field is gone or invisible, it is impossible for the user to fill it.
Maybe it is possible to don't validate it ?

Validator.java; Method checkFields :

protected boolean checkFields(ValidationCallback callback)
{
        boolean result = true;
        mHasFailed = false;
        for (ValidationHolder validationHolder : mValidationHolderList)
        {
// Patch
           if (validationHolder.getEditText() != null
                && validationHolder.getEditText().getVisibility() != View.VISIBLE)
            {
                continue;
            }
// End Patch        

            if (validationHolder.isRegexType())
            ...

Custom Validators?

So I can a add param as a class to handle complex validation? If not is there a way to validate age from a date string such as 10/20/1985?

Validation of Spinner/Spinner selection

Is it possible to validate a spinner widget directly? Trying to make sure the user selects an item from the dropdown before the form can be submitted.

Maybe I should use an invisible EditText? Or is there a more elegant solution?
Passing the spinner to the validation method by Id seems to compile and run, but nothing actually happens (which I kind of expected).

TextInputLayout validation doesn't work.

It doesn't work with the TextInputLayout validation.
Implementation:
`
Java Code

AwesomeValidation awesomeValidation = new AwesomeValidation(ValidationStyle.TEXT_INPUT_LAYOUT);

awesomeValidation.addValidation(getActivity(), R.id.test_til_email,Patterns.EMAIL_ADDRESS, R.string.error_email);

 awesomeValidation.validate()

*XML

<android.support.design.widget.TextInputLayout
        android:id="@+id/test_til_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="enter email" />
    </android.support.design.widget.TextInputLayout>

How to Add validation on dynamically added fragment editttext

I am working on an android app In which similar Fragments(each fragment containing some edit-texts) are added to activity pro-grammatically. I want to validate all fragment edit text data on activity button click event so that all data can be validated.How this can achieved?

Override for TextInputLayout seems broken

I am attempting to do something like the following, assuming _clientNameInputLayout has been initialized:
addValidation(_clientNameInputLayout, RegexTemplate.NOT_EMPTY, R.string.field_required)
but I'm getting this error:

cannot resolve method 'addValidation(TextInputLayout, String, int)'

However, if I do the following:
addValidation(_clientNameInputLayout, RegexTemplate.NOT_EMPTY, "This field is required")
the compiler is happy.
Surely my initial statement should be allowed? Or am I doing something stupid?

Label space not removed after invalid to valid state

Me again. I'm using the TextInputLayout style in this case.

Upon failed validation, the red labels appear below fields as they should, however when the user inputs valid data, if there are still validation errors, the space where the valid field's error label used to be doesn't close or disappear, causing an unwanted gap between fields in my LinearLayout dialog form.

Here is a screenshot, whereby the name field was invalid until entering Bob Jones, but the email field is still invalid and the space beneath Bob Jones still remains.
20180219_172322

NullPointerException

I keep getting this error:

NullPointerException: Attempt to invoke virtual method 'void com.basgeekball.awesomevalidation.AwesomeValidation.clear()' on a null object reference

It doesn't specify which field it has trouble with. How do I debug this error??

Igor

awesomeValidation doesnot work on fragment...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mainView = inflater.inflate(R.layout.fragment_feedback, container, false);




    initView();

    return mainView;
}

private void initView(){

    editEmail = (EditText) mainView.findViewById(R.id.edit_email);
    editMessage = (EditText) mainView.findViewById(R.id.edit_message);
    btnSend = (Button) mainView.findViewById(R.id.btn_send);
    coordinatorLayout = (CoordinatorLayout) mainView.findViewById(R.id.coordinatorLayout);
    snackBar = new SnackBar();


    awesomeValidation = new AwesomeValidation(UNDERLABEL);

    awesomeValidation.setContext(getContext());
    btnSend.setOnClickListener(this);
    addValidationToViews();




}


@Override
public void onClick(View view) {


    switch (view.getId()){

        case R.id.btn_send:

            if (awesomeValidation.validate()) {

           Toast.makeText(getContext(), "FeedBack Validation", Toast.LENGTH_SHORT).show();

            }

            break;
    }
}

private void addValidationToViews(){

    awesomeValidation.addValidation(getActivity(),R.id.edit_email, Patterns.EMAIL_ADDRESS, R.string.invalid_email);
    awesomeValidation.addValidation(getActivity(), R.id.edit_message, RegexTemplate.NOT_EMPTY, R.string.invalid_name);

}

///////////////////////////////////////////////
always return true.

how to support confirm email case

I want to add confirm edittext if two edittext value not equal I will show error message,

I think If I can show error message programmatically without any pattern I can do this .

How to add multiple validations

I want to add two validations like first one is RegexTemplate.NOT_EMPTY and second one is required length
but it's showing only second validation message on validate , but i want to saw only first RegexTemplate.NOT_EMPTY message if field is empty.

How can i do this?

UNDERLABEL doesn't work on ConstraintLayout

device-2017-07-09-134358

For given layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="anddev.mat.pckplace.CreateAccount">

    <EditText
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textEmailAddress"
        android:text="[email protected]"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPassword"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/email" />

    <Button
        android:id="@+id/joinButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Join"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.185" />

</android.support.constraint.ConstraintLayout>

error getColor()

hi.. get error like this
Process: com.belisip.affiliate, PID: 10687
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.getColor(int)' on a null object reference
at android.support.v4.content.ContextCompatApi23.getColor(ContextCompatApi23.java:32)
at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:432)
at com.basgeekball.awesomevalidation.validators.UnderlabelValidator.trigger(SourceFile:52)
at com.basgeekball.awesomevalidation.AwesomeValidation.validate(SourceFile:139)
at com.belisip.affiliate.fragments.AlamatPemesan$4.onClick(AlamatPemesan.java:142)
at android.view.View.performClick(View.java:6213)
at android.widget.TextView.performClick(TextView.java:11074)
at android.view.View$PerformClick.run(View.java:23645)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6692)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

an on line 142 error is:
next.setOnClickListener(new View.OnClickListener() {
@OverRide
public void onClick(View view) {
if(mAwesomeValidation.validate()) { <-- line 142

                ((CheckOut) getActivity()).next();
            }
        }
    });

i don't know whats wrong....
any suggestion ???

mAwesomeValidation.validate()

if (mAwesomeValidation.validate()) {
//awsome validator implemented inside fragment, gives below error

Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

Gradle can't download your library

I write " compile 'com.github.thyrlian:AwesomeValidation:3ef10cd2c8' ''
in my build.gradle file, but it prompts this:
"Failed to resolve: com.github.thyrlian:AwesomeValidation:3ef10cd2c8

Can anyone help me with this error?

Scroll to error field

Is there a way to scroll and focus on the error field? Right now, all invalid fields are red, but the page stays scrolled to the bottom when it's a long form.

Thank you,
Igor

Can not set Compound Drawable

I can set compound drwables onCreate, and also I change the drwable resource file on button click, but after calling validate method, I can not change the drawable resource. Can you help me, I used COLORATION validator, is it the reason ?

Double Validation with different Error String

can I use two or more validator in one TextInputLayout

validator.addValidation(this, R.id.tilEmail, RegexTemplate.NOT_EMPTY, R.string.err_email_null); validator.addValidation(this, R.id.tilEmail, Patterns.EMAIL_ADDRESS, R.string.err_email);

while the tilEmail is EMPTY the error just showing Patterns.EMAIL_ADDRESS with err_email not err_email_null

Range for hours

Hi,
I'm trying to implement a validation for a TimePickerDialog, and I didn't find a way to properly set a Range, while showing a nice text on the EditText.
Here's my code :
mAwesomeValidation.addValidation(this, R.id.time, Range.closed(hour, hour + MAX_DURATION_PARTY_IN_HOURS), R.string.err_time);
To resolve the issue, I have to set the EditText to just the "hour", and I noticed in the code you validate based on the EditText, so how could I solve this issue ?
Thank you.

To-Do List

  • complex layout (horizontal orientation)
  • change EditText's underline color for UnderlabelValidator
  • use same padding as EditText for underline
  • overload addValidation to support range validation
  • return ArrayList instead of boolean at Validator#trigger() ???
  • add more regex constants to RegexTemplate
  • support android.util.Patterns
  • pair
  • ignore invisible fields
  • add option to clear individual error on text change

Validation negative numbers.

Valid.addValidation(MyEditText,Range.closed(-20000f,20000f),"Err");

In MyEditText i typed -5 and it didn't validate.

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.