Android Form Validation using Android Saripaar library Tutorial

Udemy Generic 728x90

Objective

In this tutorial we learn how to validate the Form using Android Saripaar Library in Android Application through simple example.

 

 

We define a rule to test if the provided string matches a specific format and then apply that rule to test the input string entered by user in an input box. If given string does not satisfy the validation rule then display an error message as notification. This whole process is known as Form Validation.

In this tutorial, we will use Android Saripaar library to validate the input fields of the form. Using this library, we can apply following type of validation rules in our form:

  • Email: Checks whether input field contains an email address.
  • Password: Checks whether input field satisfies custom rules defined to create a new password.
  • Confirm Password: Checks whether the input string matches the input of password field.
  • Alpha Numeric:- Checks whether input contains Alphanumeric string.

 

Step 2

Create New Project

Create a new Project in Android Studio, goto File ⇒ New ⇒ New Projects.

 

Step 3

Adding Library as Dependency

We will use Android Saripaar library in the project to apply validation on EditText fields. Open build.gradle(app module) file and add following line to compile Android Saripaar library in your project.

<br />
dependencies {<br />
    ....<br />
    compile 'com.mobsandgeeks:android-saripaar:1.0.3'<br />
    ...<br />
}<br />

 

Step 4

Create Layout

Next, we will create a simple form by using EditText and Button widget. So, add EditText widget to get input string and Button to submit the form. Use the following code in the activity_main.xml file.

<br />
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br />
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br />
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br />
    android:layout_width=&quot;match_parent&quot;<br />
    android:layout_height=&quot;match_parent&quot;<br />
    android:paddingBottom=&quot;@dimen/activity_vertical_margin&quot;<br />
    android:paddingLeft=&quot;@dimen/activity_horizontal_margin&quot;<br />
    android:paddingRight=&quot;@dimen/activity_horizontal_margin&quot;<br />
    android:paddingTop=&quot;@dimen/activity_vertical_margin&quot;<br />
    tools:context=&quot;app.formvalidation4.MainActivity&quot;&gt;</p>
<p>    &lt;EditText<br />
        android:id=&quot;@+id/email&quot;<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:hint=&quot;Email&quot; /&gt;</p>
<p>    &lt;EditText<br />
        android:id=&quot;@+id/password&quot;<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:layout_below=&quot;@+id/email&quot;<br />
        android:hint=&quot;Password&quot; /&gt;</p>
<p>    &lt;EditText<br />
        android:id=&quot;@+id/conf_password&quot;<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:layout_below=&quot;@+id/password&quot;<br />
        android:hint=&quot;Confirm Password&quot; /&gt;</p>
<p>    &lt;EditText<br />
        android:id=&quot;@+id/phone&quot;<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:layout_below=&quot;@+id/conf_password&quot;<br />
        android:hint=&quot;Phone number&quot; /&gt;</p>
<p>    &lt;EditText<br />
        android:id=&quot;@+id/alphnumeric&quot;<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:layout_below=&quot;@+id/phone&quot;<br />
        android:hint=&quot;Alpha Numeric (max lenght 12)&quot; /&gt;</p>
<p>    &lt;Button<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:text=&quot;submit&quot;<br />
        android:layout_below=&quot;@+id/alphnumeric&quot;<br />
        android:onClick=&quot;onClick&quot;/&gt;</p>
<p>&lt;/RelativeLayout&gt;</p>
<p>

form-validation

 

Step 5

Implement Validation Listener

To apply validation rules, we need to implement validation listener in MainActivity file. To implement validation listeners, we have to use onValidationSucceeded() method to perform further operation on success of validation and also add onValidationFailed() method to display an error message if input string failed to satisfy validation rule.

<br />
public class MainActivity extends AppCompatActivity<br />
                 implements Validator.ValidationListener {</p>
<p>    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);<br />
    }</p>
<p>   /**<br />
     * To perform the operation, when all input field satisfy the validation rule.<br />
     */<br />
   @Override<br />
    public void onValidationSucceeded() {<br />
        Toast.makeText(this, &quot;Yay! we got it right!&quot;, Toast.LENGTH_SHORT).show();<br />
    }<br />
   /**<br />
    *  To display the notification message, when any one of the input<br />
    *  filed is not satisfy validation rule<br />
    */<br />
    public void onValidationFailed(View view, Rule&lt;?&gt; rule) {</p>
<p>        final String failureMessage = rule.getFailureMessage();<br />
        if (view instanceof EditText) {<br />
            EditText failed = (EditText) view;<br />
            failed.requestFocus();<br />
            failed.setError(failureMessage);<br />
        } else {<br />
            Toast.makeText(getApplicationContext(), failureMessage, Toast.LENGTH_SHORT).show();<br />
        }<br />
    }<br />
}<br />

 

Step 6

Add Validation Rules

Next, we need to apply validation rules on EditText fields. This library use Annotations to define validation rules. So, we have to define order number of the Annotations because validation rule apply according to its order number and also add an error message to display an error on the screen. These are the following Annotations defined in library to create validation rules :

  • @Required:- Ensures that the field is not empty
  • @Email:- Ensures that the field is valid Email Address
  • @Password:- Ensure that alpha numeric
  • @ConfirmPassword:- Match string with Password field.
  • @TextRule:- Define the custom rule for the validation

<br />
public class MainActivity extends AppCompatActivity<br />
                 implements Validator.ValidationListener {</p>
<p>    // Ensures that the field is not empty.<br />
    @Required(order = 1)</p>
<p>    // Define input should be email id, an error message and order number is 2<br />
    @Email(order = 2, message = &quot;Please Check and Enter a valid Email Address&quot;)<br />
    private EditText email;</p>
<p>    // set the password filed which is alpha numeric and order number is 3.<br />
    @Password(order = 3)</p>
<p>    // set the rule for password field that minimum length is 6 and maximum lenght is 15.<br />
    @TextRule(order = 4, minLength = 6, maxLength = 15, message = &quot;Enter at least 6 characters.&quot;)<br />
    private EditText password;</p>
<p>    // Match with the passord input string<br />
    @ConfirmPassword(order = 5)<br />
    private EditText confirmPassword;</p>
<p>     // Ensures that the field is not empty.<br />
    @Required(order = 6)</p>
<p>    // Set the rule for input is only support numeric.<br />
    @NumberRule(order = 7, message = &quot;Enter Phone Number in Numeric&quot;,<br />
                type = NumberRule.NumberType.LONG)</p>
<p>    // Set the input value must be greater than 10 and smaller than 14.<br />
    @TextRule(order = 8,<br />
              message = &quot;Enter valid Phone Number&quot;,<br />
              minLength = 10, maxLength = 14)<br />
    private EditText phone;</p>
<p>    // Set the rules that maximum input length must be 12 and field support alphanumeric<br />
    @TextRule(order = 9, maxLength = 12,<br />
              message = &quot;Invalid NRIC (max 12 numbers)&quot;)<br />
    @Required(order = 10)<br />
    EditText alphnumeric;</p>
<p>    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);<br />
   }</p>
<p>  /**<br />
   * To perform the operation, when all input field satisfy the validation rule.<br />
   */<br />
   @Override<br />
    public void onValidationSucceeded() {<br />
        Toast.makeText(this, &quot;Yay! we got it right!&quot;, Toast.LENGTH_SHORT).show();<br />
    }<br />
   /**<br />
    *  To display the notification message, when any one of the input -<br />
    *  filed is not satisfy validation rule<br />
    */<br />
    public void onValidationFailed(View view, Rule&lt;?&gt; rule) {</p>
<p>        final String failureMessage = rule.getFailureMessage();<br />
        if (view instanceof EditText) {<br />
            EditText failed = (EditText) view;<br />
            failed.requestFocus();<br />
            failed.setError(failureMessage);<br />
        } else {<br />
            Toast.makeText(getApplicationContext(), failureMessage, Toast.LENGTH_SHORT).show();<br />
        }<br />
    }</p>
<p>}<br />

 

Step 7

Initialize the EditText

We need to initialize EditText to get input string by the user.

<br />
public class MainActivity extends AppCompatActivity<br />
                 implements Validator.ValidationListener {</p>
<p>    // Ensures that the field is not empty.<br />
    @Required(order = 1)</p>
<p>    // Define input should be email id, an error message and order number is 2<br />
    @Email(order = 2, message = &quot;Please Check and Enter a valid Email Address&quot;)<br />
    private EditText email;</p>
<p>    // set the password filed which is alpha numeric and order number is 3.<br />
    @Password(order = 3)</p>
<p>    // set the rule for password field that minimum length is 6 and maximum lenght is 15.<br />
    @TextRule(order = 4, minLength = 6, maxLength = 15, message = &quot;Enter at least 6 characters.&quot;)<br />
    private EditText password;</p>
<p>    // Match with the passord input string<br />
    @ConfirmPassword(order = 5)<br />
    private EditText confirmPassword;</p>
<p>     // Ensures that the field is not empty.<br />
    @Required(order = 6)</p>
<p>    // Set the rule for input is only support numeric.<br />
    @NumberRule(order = 7, message = &quot;Enter Phone Number in Numeric&quot;,<br />
                type = NumberRule.NumberType.LONG)</p>
<p>    // Set the input value must be greater than 10 and smaller than 14.<br />
    @TextRule(order = 8,<br />
              message = &quot;Enter valid Phone Number&quot;,<br />
              minLength = 10, maxLength = 14)<br />
    private EditText phone;</p>
<p>    // Set the rules that maximum input length must be 12 and field support alphanumeric<br />
    @TextRule(order = 9, maxLength = 12,<br />
              message = &quot;Invalid NRIC (max 12 numbers)&quot;)<br />
    @Required(order = 10)<br />
    EditText alphnumeric;</p>
<p>    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        email = (EditText) findViewById(R.id.email);<br />
        password = (EditText)findViewById(R.id.password);<br />
        confirmPassword = (EditText) findViewById(R.id.conf_password);<br />
        alphnumeric = (EditText) findViewById(R.id.alphnumeric);<br />
        phone = (EditText) findViewById(R.id.phone);<br />
   }</p>
<p>  /**<br />
   * To perform the operation, when all input field satisfy the validation rule.<br />
   */<br />
   @Override<br />
    public void onValidationSucceeded() {<br />
        Toast.makeText(this, &quot;Yay! we got it right!&quot;, Toast.LENGTH_SHORT).show();<br />
    }<br />
   /**<br />
    *  To display the notification message, when any one of the input -<br />
    *  filed is not satisfy validation rule<br />
    */<br />
    public void onValidationFailed(View view, Rule&lt;?&gt; rule) {</p>
<p>        final String failureMessage = rule.getFailureMessage();<br />
        if (view instanceof EditText) {<br />
            EditText failed = (EditText) view;<br />
            failed.requestFocus();<br />
            failed.setError(failureMessage);<br />
        } else {<br />
            Toast.makeText(getApplicationContext(), failureMessage, Toast.LENGTH_SHORT).show();<br />
        }<br />
    }</p>
<p>}<br />

 

Step 8

Call Validation Listener

We need to call validation listener to display message on both success and failure scenario. So, create a Validator() object and call setValidationListener() method.

<br />
public class MainActivity extends AppCompatActivity<br />
                 implements Validator.ValidationListener {</p>
<p>    Validator validator;<br />
    // Ensures that the field is not empty.<br />
    @Required(order = 1)</p>
<p>    // Define input should be email id, an error message and order number is 2<br />
    @Email(order = 2, message = &quot;Please Check and Enter a valid Email Address&quot;)<br />
    private EditText email;</p>
<p>    // set the password filed which is alpha numeric and order number is 3.<br />
    @Password(order = 3)</p>
<p>    // set the rule for password field that minimum length is 6 and maximum lenght is 15.<br />
    @TextRule(order = 4, minLength = 6, maxLength = 15, message = &quot;Enter at least 6 characters.&quot;)<br />
    private EditText password;</p>
<p>    // Match with the passord input string<br />
    @ConfirmPassword(order = 5)<br />
    private EditText confirmPassword;</p>
<p>     // Ensures that the field is not empty.<br />
    @Required(order = 6)</p>
<p>    // Set the rule for input is only support numeric.<br />
    @NumberRule(order = 7, message = &quot;Enter Phone Number in Numeric&quot;,<br />
                type = NumberRule.NumberType.LONG)</p>
<p>    // Set the input value must be greater than 10 and smaller than 14.<br />
    @TextRule(order = 8,<br />
              message = &quot;Enter valid Phone Number&quot;,<br />
              minLength = 10, maxLength = 14)<br />
    private EditText phone;</p>
<p>    // Set the rules that maximum input length must be 12 and field support alphanumeric<br />
    @TextRule(order = 9, maxLength = 12,<br />
              message = &quot;Invalid NRIC (max 12 numbers)&quot;)<br />
    @Required(order = 10)<br />
    EditText alphnumeric;</p>
<p>    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        email = (EditText) findViewById(R.id.email);<br />
        password = (EditText)findViewById(R.id.password);<br />
        confirmPassword = (EditText) findViewById(R.id.conf_password);<br />
        alphnumeric = (EditText) findViewById(R.id.alphnumeric);<br />
        phone = (EditText) findViewById(R.id.phone);</p>
<p>        /* Create Validator object to -<br />
         * call the setValidationListener method of Validator class.<br />
         */<br />
        validator = new Validator(this);<br />
        // Call the validation listener method.<br />
        validator.setValidationListener(this);<br />
   }</p>
<p>  /**<br />
   * To perform the operation, when all input field satisfy the validation rule.<br />
   */<br />
   @Override<br />
    public void onValidationSucceeded() {<br />
        Toast.makeText(this, &quot;Yay! we got it right!&quot;, Toast.LENGTH_SHORT).show();<br />
    }<br />
   /**<br />
    *  To display the notification message, when any one of the input -<br />
    *  filed is not satisfy validation rule<br />
    */<br />
    public void onValidationFailed(View view, Rule&lt;?&gt; rule) {</p>
<p>        final String failureMessage = rule.getFailureMessage();<br />
        if (view instanceof EditText) {<br />
            EditText failed = (EditText) view;<br />
            failed.requestFocus();<br />
            failed.setError(failureMessage);<br />
        } else {<br />
            Toast.makeText(getApplicationContext(), failureMessage, Toast.LENGTH_SHORT).show();<br />
        }<br />
    }<br />
}<br />

 

Step 9

Validate the Form

We need to validate the form when user clicks the submit button. So, create a callback onClick() method and call validate() method of Validator class.

<br />
public class MainActivity extends AppCompatActivity<br />
                 implements Validator.ValidationListener {</p>
<p>    Validator validator;<br />
    // Ensures that the field is not empty.<br />
    @Required(order = 1)</p>
<p>    // Define input should be email id, an error message and order number is 2<br />
    @Email(order = 2, message = &quot;Please Check and Enter a valid Email Address&quot;)<br />
    private EditText email;</p>
<p>    // set the password filed which is alpha numeric and order number is 3.<br />
    @Password(order = 3)</p>
<p>    // set the rule for password field that minimum length is 6 and maximum lenght is 15.<br />
    @TextRule(order = 4, minLength = 6, maxLength = 15, message = &quot;Enter at least 6 characters.&quot;)<br />
    private EditText password;</p>
<p>    // Match with the passord input string<br />
    @ConfirmPassword(order = 5)<br />
    private EditText confirmPassword;</p>
<p>     // Ensures that the field is not empty.<br />
    @Required(order = 6)</p>
<p>    // Set the rule for input is only support numeric.<br />
    @NumberRule(order = 7, message = &quot;Enter Phone Number in Numeric&quot;,<br />
                type = NumberRule.NumberType.LONG)</p>
<p>    // Set the input value must be greater than 10 and smaller than 14.<br />
    @TextRule(order = 8,<br />
              message = &quot;Enter valid Phone Number&quot;,<br />
              minLength = 10, maxLength = 14)<br />
    private EditText phone;</p>
<p>    // Set the rules that maximum input length must be 12 and field support alphanumeric<br />
    @TextRule(order = 9, maxLength = 12,<br />
              message = &quot;Invalid NRIC (max 12 numbers)&quot;)<br />
    @Required(order = 10)<br />
    EditText alphnumeric;</p>
<p>    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        email = (EditText) findViewById(R.id.email);<br />
        password = (EditText)findViewById(R.id.password);<br />
        confirmPassword = (EditText) findViewById(R.id.conf_password);<br />
        alphnumeric = (EditText) findViewById(R.id.alphnumeric);<br />
        phone = (EditText) findViewById(R.id.phone);</p>
<p>        validator = new Validator(this);<br />
        validator.setValidationListener(this);<br />
   }</p>
<p>  /**<br />
   * To perform the operation, when all input field satisfy the validation rule.<br />
   */<br />
   @Override<br />
    public void onValidationSucceeded() {<br />
        Toast.makeText(this, &quot;Yay! we got it right!&quot;, Toast.LENGTH_SHORT).show();<br />
    }<br />
   /**<br />
    *  To display the notification message, when any one of the input -<br />
    *  filed is not satisfy validation rule<br />
    */<br />
    public void onValidationFailed(View view, Rule&lt;?&gt; rule) {</p>
<p>        final String failureMessage = rule.getFailureMessage();<br />
        if (view instanceof EditText) {<br />
            EditText failed = (EditText) view;<br />
            failed.requestFocus();<br />
            failed.setError(failureMessage);<br />
        } else {<br />
            Toast.makeText(getApplicationContext(), failureMessage, Toast.LENGTH_SHORT).show();<br />
        }<br />
    }<br />
    // this method is used when the user submit the form<br />
    public void onClick(View view){<br />
        // Apply validation rule on the EditText<br />
        validator.validate();<br />
    }</p>
<p>}<br />

 

formvalidation

Udemy Generic 728x90

Spread the word. Share this post!

  • Guillermo Vargas

    Why not use this version ‘com.mobsandgeeks:android-saripaar:2.0.3′ ?

  • Vivek Mishra

    Worst possible formatting for a blog post. Congrats