UI form validation library for Android

Related tags

Utility android java
Overview

Android Saripaar v2 Android Arsenal

Logo

சரிபார் - sari-paar (Tamil for "to check", "verify" or "validate")

Android Saripaar is a simple, feature-rich and powerful rule-based UI form validation library for Android. It is the SIMPLEST UI validation library available for Android.

Why Android Saripaar?

  • Built on top of Apache Commons Validator, a validation framework with proven track record on the web, desktop and mobile platforms.
  • Declarative style validation using Annotations.
  • Extensible, now allows Custom Annotations.
  • Synchronous and Asynchronous validations, you don't have to worry about threading.
  • Supports both BURST and IMMEDIATE modes.
  • Works with Stock Android Widgets, no custom view dependencies.
  • Isolates validation logic using rules.
  • Compatible with other annotation-based libraries and frameworks such as ButterKnife, AndroidAnnotations, RoboGuice, etc.,

Quick Start

Step 1 - Annotate your widgets using Saripaar Annotations

@NotEmpty
@Email
private EditText emailEditText;

@Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;

@ConfirmPassword
private EditText confirmPasswordEditText;

@Checked(message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;

The annotations are self-explanatory. The @Order annotation is required ONLY when performing ordered validations using Validator.validateTill(View) and Validator.validateBefore(View) or in IMMEDIATE mode.

Step 2 - Instantiate a new Validator

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Code…

    validator = new Validator(this);
    validator.setValidationListener(this);

    // More code…
}

You will need a Validator and a ValidationListener for receiving callbacks on validation events.

Step 3 - Implement a ValidationListener

public class RegistrationActivity extends Activity implements ValidationListener {

    // Code…

    @Override
    public void onValidationSucceeded() {
        Toast.makeText(this, "Yay! we got it right!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(this);

            // Display error messages ;)
            if (view instanceof EditText) {
                ((EditText) view).setError(message);
            } else {
                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            }
        }
    }
}
  • onValidationSucceeded() - Called when all your views pass all validations.
  • onValidationFailed(List<ValidationError> errors) - Called when there are validation error(s).

Step 4 - Validate

registerButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        validator.validate();
    }
});

The Validator.validate() call runs the validations and returns the result via appropriate callbacks on the ValidationListener. You can run validations on a background AsyncTask by calling the Validator.validate(true) method.

Saripaar X

If you are looking for country-specific annotations, checkout the Saripaar X project. The extensions project is in its early stages and needs contributors. Feel free to contribute.

Maven

<dependency>
    <groupId>com.mobsandgeeks</groupId>
    <artifactId>android-saripaar</artifactId>
    <version>(latest version)</version>
</dependency>

Gradle

dependencies {
    compile 'com.mobsandgeeks:android-saripaar:(latest version)'
}

Snapshots

In your {project_base}/build.gradle file, include the following.

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
    }
}

ProGuard

Exclude Saripaar classes from obfuscation and minification. Add the following rules to your proguard-rules.pro file.

-keep class com.mobsandgeeks.saripaar.** {*;}
-keep @com.mobsandgeeks.saripaar.annotation.ValidateUsing class * {*;}

Evolution

For those interested in finding out how v2 evolved from v1, watch this (~20 second) video.

Using Saripaar?

Tweet me with your Google Play URL and I'll add your app to the list :)

Icon App Icon App Icon App
Wikipedia Wikipedia Beta Mizuno Baton
Fetch HealtheMinder MomMe
Feelknit StreetBarz Roast Me
Pipe Snagajob Tatva Moksh Lakshya

Wiki

Please visit the wiki for a complete guide on Android Saripaar.

License

Copyright 2012 - 2015 Mobs & Geeks

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Saripaar Logo © 2013 - 2015, Mobs & Geeks.

Comments
  • Multiple rules for one view

    Multiple rules for one view

    Your library is great and I am just playing around with V2.

    Can I somehow stop the validation process for a view with multiple rules after the first error has occured?

    I have a use case with two rules for one edit text field. The first rule checks if the user name is at least 5 characters long. The second then calls a backend service to check if this user name is still avaliable. So I only want the second rule to be fired if the first one is okay.

    Sorry if I missed something but based on the code in the Validator I have not seen such an option.

    opened by ghost 33
  • No way to set order for custom rules

    No way to set order for custom rules

    Rules ordering is done on validation and custom rules adding occurs before. If so, custom rules always have more priority and that's not true. Maybe, it's better to store order inside the Rule? So developer could add custom rules at runtime with proper priority.

    opened by almozavr 24
  • Validate Only If Fields Are Not Empty

    Validate Only If Fields Are Not Empty

    Hi,

    Is there anyway to tell Saripaar to validate fields only if they're not empty? If not, please implement this feature.

    Thanks for this great library.

    opened by meness 15
  • Validator.registerAdapter() should not be static (or leaks are easy to follow)

    Validator.registerAdapter() should not be static (or leaks are easy to follow)

    I beleive that it would be better to make Validator.registerAdapter() non-static method.

    I just had whole Activity context leaked because of this method is static. If you do something like this in your activity:

    void onCreate() {
      Validator.registerAdapter(MyCustomView.class, new ViewDataAdapter<MyCustomView, String>() {
        public String getData(MyCustomView view) {
           return view.getCustomText();
        }
       validator = new Validator();
    }
    

    then you automatically leak your Context, because it gets captured by anonymous class. And using anonymous classes for this kind of things is very common. So using static here makes it very easy to introduce a leak.

    Besides by looking at the sources I don't see why this method needs to be global. Validator class seems to be designed to be used in local scope, i.e. inside an activity lifetime, so it seems that registerAdapter should live in that scope too, i.e. be non static.

    opened by dimsuz 15
  • Password validation failure

    Password validation failure

    I have such an EditText: @Password @Size(min = 6, message = "Enter at least 8 characters.") EditText editTxtPassword;

    this rule works, except the case if my pass long enough. When my edittext has string with 6 chars It returns emty error

    opened by PenzK 13
  • Validating hidden fields

    Validating hidden fields

    Hi Ragunath,

    I understand from reading other issues that it is a feature. However, we've got a view that is layouted similar to an expandable list where the user can collapse sections of the view. Within these partly collapsed sections are input fields that we need to include in the validation. By collapsing a section all subviews are hidden (visibility=GONE), including the input fields.

    I understand from your code that the check "if (view.isShown() & view.isEnabled()) ..." is fix coded and there is no configurable item that enables or disables this feature.

    What do you think of making this configurable like "checkHidden = true" on rule level (with a default of false) or so? Or woudn't it be sufficient to change that if statement to "if (view.isEnabled())". Somebody who wants to exclude hidden fields from validation could still disable them.

    As for now we are using @NotEmpty checks only on that view.

    Any help is appreciated.

    Cheers Hermann

    opened by HermannK 12
  • Synchronous validation response

    Synchronous validation response

    There are cases where you want to run validation and get the response in a single thread. For example, when the user hits 'Done' on the keyboard on the last field you might want to validate all fields before submitting data to the server.

    As far as I can see the only way to find out the validation result is in the onValidationSucceeded() callback, but in this multithreaded environment that doesn't know the trigger context (user just pressed 'Done' on the keyboard) so you end up having to set hacky workarounds with state variables in the Activity class which is undesirable.

    Maybe validate(false) could return List<ValidationError> ?

    opened by molexx 10
  • Is Annotations included in jar file?

    Is Annotations included in jar file?

    Hi Sir, I came across with your library and I want to try it out. In your instruction Quick Start-step 1, there is an annotation, @NotEmpty , and when I open the link of your annotations, I can see several classes.

    I tried above instruction but I can't find the class @NotEmpty, so I tried copying the code in your NotEmpty.class and create a copy in my project, but @ValidateUsing(NotEmptyRule.class) could not be found either.

    So, I downloaded your main project and I found all those files.

    My question is, why I could not find those files in your jar? do I need to include the source as dependency in my project?

    Thank you so much.

    opened by chkm8 10
  • Attempt to invoke virtual method 'void com.mobsandgeeks.saripaar.ValidationContext.setViewRulesMap(java.util.Map)' on a null object reference

    Attempt to invoke virtual method 'void com.mobsandgeeks.saripaar.ValidationContext.setViewRulesMap(java.util.Map)' on a null object reference

    I am using this library https://github.com/ragunathjawahar/android-saripaar to apply validations on my input fields like non empty, email etc.

    I have two input fields and this is how I am applying validations. It is crashing my application. I checked validator variable is not null

    MainActivity.java

    @NotEmpty
    private TextInputLayout client_id_input_layout;
    
    @NotEmpty
    private TextInputLayout access_code_input_layout;
    
    @Inject
    Validator validator;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	....
    
    	validator.setValidationListener(this);
    }
    
    @Override
    public void onClick(View view) {
    	if(isOnline())
    		validator.validate();
    	else
    		Snackbar.make(mCoordinatorLayout, getString(R.string.network_error), Snackbar.LENGTH_LONG).show();
    }
    

    Validator.java

    @Module
    public class Validator {
    
    	@Provides
    	@Singleton
    	com.mobsandgeeks.saripaar.Validator providesValidator(Application application) {
    		return new com.mobsandgeeks.saripaar.Validator(application);
    	}
    }
    

    StackTrace

    Process: com.icici.iciciappathon, PID: 4555
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mobsandgeeks.saripaar.ValidationContext.setViewRulesMap(java.util.Map)' on a null object reference
       at com.mobsandgeeks.saripaar.Validator.createRulesSafelyAndLazily(Validator.java:479)
       at com.mobsandgeeks.saripaar.Validator.validate(Validator.java:330)
       at com.mobsandgeeks.saripaar.Validator.validate(Validator.java:295)
       at com.icici.iciciappathon.login.AuthenticationActivity.onClick(AuthenticationActivity.java:102)
       at android.view.View.performClick(View.java:5609)
       at android.view.View$PerformClick.run(View.java:22259)
       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:6077)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    
    opened by ajaysaini-sgvu 9
  • Validator constructor should warn if not passing in fragment or activity

    Validator constructor should warn if not passing in fragment or activity

    in Validator class:

        public Validator(final Object controller) {
            assertNotNull(controller, "controller");
            mController = controller;
            mValidationMode = Mode.BURST;
            mSequenceComparator = new SequenceComparator();
            mViewValidatedAction = new DefaultViewValidatedAction();
    
            // Instantiate a ValidationContext
            if (controller instanceof Activity) {
                mValidationContext = new ValidationContext((Activity) controller);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB
                    && controller instanceof Fragment) {
                Activity activity = ((Fragment) controller).getActivity();
                mValidationContext = new ValidationContext(activity);
            }
            // Else, lazy init ValidationContext in #getRuleAdapterPair(Annotation, Field)
            // or void #put(VIEW, QuickRule<VIEW>) by obtaining a Context from one of the
            // View instances.
        }
    

    If I pass in something other than Fragment or Activity I'll eventually get NPE when trying to access a ValidationContext:

    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mobsandgeeks.saripaar.ValidationContext.setViewRulesMap(java.util.Map)' on a null object reference
    

    I see two options:

    1. the simple option is to just warn me with specific RTE
    2. make this constructor private and overload with constructors that take in fragment and activities:
    public Validator(Activity controller) {
        this(controller);
        this.mValidationContext = new ValidationContext((Activity)controller);
    }
    
    public Validator(Fragment controller) {
       this(controller);
        if(Build.VERSION.SDK_INT >= 11) {
            Activity activity = ((Fragment)controller).getActivity();
            this.mValidationContext = new ValidationContext(activity);
        } else {
            throw new RuntimeException("...")
        }
    }
    
    private Validator(Object controller) {
        assertNotNull(controller, "controller");
        this.mController = controller;
        this.mValidationMode = Validator.Mode.BURST;
        this.mSequenceComparator = new SequenceComparator();
        this.mViewValidatedAction = new DefaultViewValidatedAction();
    }
    
    opened by tir38 9
  • Dynamic validation

    Dynamic validation

    Hello, first of all thank you so much such perfect library.

    I am new with your library I have conditional based some field, can I validate that as well ? if yes then how.

    Thanks, Ronak Amlani

    opened by ronakamlani 9
  • ##How can i add custom annotation to your library.

    ##How can i add custom annotation to your library.

    In my case, I would like to check if the first Edittext matches with the second Edittext. But for this case, I can't use the @ConfirmPassword annotation since this is not a password I want to check the pin.

    opened by sawepeter 0
  • Support multiple module project

    Support multiple module project

    When i'm using android-saripaar in project with one module it's ok but if i'm using this library with multiple module project the problem is R,java is not final in library modules so i think you need to support R2 or create custom R class to use it with android-saripaar

    opened by mnayef95 2
Releases(android-saripaar-2.0.3)
Owner
Ragunath Jawahar
Ragunath Jawahar
Simple-Claim-Form - Android App for creating a simple dynamic form with MVVM architecture

Simple-Claim-Form Android App for creating a simple dynamic form with MVVM archi

Shubham Gangpuri 1 Aug 14, 2022
Compose easy forms validation library

Compose EasyForms Focus on building your form UI while the library do the heavy work for you. Features Built in support for most of the Form widgets i

Kosh Sergani 24 Jul 18, 2022
Kotlin validation with a focus on readability

kommodus Kotlin validation with a focus on readability import com.github.kommodus.constraints.* import com.github.kommodus.Validation data class Test

Serhii Shobotov 0 Dec 12, 2021
Validator - Notify type based validation for input fields.

Validator - Notify type based validation for input fields.

Mustafa Yiğit 57 Dec 8, 2022
Sample project displaying process of OTP validation using firebase

OTP-Validation-using-firebase Sample project displaying process of OTP validation using firebase Screenshots Concepts used Integrated Firebase sdk for

Ankita Gaba 2 Jun 18, 2022
Form Validator Library for Android

Android-Validator Form Validator Library for Android [](https://flattr.com/submit/auto?user_id=throrin19&url=https://github.com/throrin19/Android-Vali

Benjamin Besse 449 Dec 17, 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