Android Form Validation using ValidationKomensky library Tutorial

Udemy Generic 728x90

Objective

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

 

 


 

In Form validation, we apply validation rules on the input box. We validate the input data with custom rules and if data does not satisfy any of the validation rule then we display an error message.

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

  • Person name : Checks whether input field contains a valid name.
  • Email : Checks whether input field contains an email address.
  • Numeric value : Checks whether the field contains only numeric value
  • Spinner : Ensure that the spinner is not empty.
  • Min Value : Ensure that value of the input field is not smaller than min value.

 

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 ValidationKomensky library in the project to apply the validation on the EditText fields. Open build.gradle(app module) file and add following line to compile the ValidationKomensky library in your project.

<br />
dependencies {<br />
    ....<br />
    compile 'eu.inmite.android.lib:android-validation-komensky:[email protected]'<br />
    ...<br />
}<br />

 

Step 4

Create Layout

Next, we will create a simple form by using EditText, Button and Spinner widget. So, add EditText widget to get input string and Button to submit the form and Spinner to show drop down list. 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 />
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&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.formvalidation5.MainActivity&quot;&gt;</p>
<p>    &lt;LinearLayout<br />
        android:layout_width=&quot;match_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:orientation=&quot;vertical&quot; &gt;</p>
<p>        &lt;EditText<br />
            android:id=&quot;@+id/name&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;wrap_content&quot;<br />
            android:hint=&quot;Name&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;<br />
            android:inputType=&quot;textEmailAddress&quot;/&gt;</p>
<p>        &lt;EditText<br />
            android:id=&quot;@+id/participants&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;wrap_content&quot;<br />
            android:hint=&quot;No. of Participants&quot;<br />
            android:inputType=&quot;number&quot;/&gt;</p>
<p>        &lt;EditText<br />
            android:id=&quot;@+id/min_number&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;wrap_content&quot;<br />
            android:hint=&quot;Min no value 5.5 &quot;<br />
            android:inputType=&quot;number&quot;/&gt;</p>
<p>        &lt;EditText<br />
            android:id=&quot;@+id/count_number&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;wrap_content&quot;<br />
            android:hint=&quot;Integer &quot;<br />
            android:inputType=&quot;number&quot;/&gt;</p>
<p>        &lt;Spinner<br />
            android:id=&quot;@+id/spinner&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;wrap_content&quot;<br />
            android:spinnerMode=&quot;dropdown&quot;/&gt;</p>
<p>        &lt;Button<br />
            android:id=&quot;@+id/submit&quot;<br />
            android:layout_width=&quot;match_parent&quot;<br />
            android:layout_height=&quot;wrap_content&quot;<br />
            android:text=&quot;submit&quot;<br />
            android:onClick=&quot;validate&quot;/&gt;</p>
<p>    &lt;/LinearLayout&gt;</p>
<p>&lt;/RelativeLayout&gt;</p>
<p>

validationform
 

Step 5

Create Array list

Using this library, we can validate whether spinner drop down list is empty or not. Hence, we need to add a list in the spinner. So, create a new arrays.xml file in the /res/values directory and within this file add a list of items. Use the following code:

<br />
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br />
&lt;resources&gt;<br />
    &lt;string-array name=&quot;demo_types&quot;&gt;<br />
        &lt;item&gt;&lt;/item&gt;<br />
        &lt;item&gt;Work&lt;/item&gt;<br />
        &lt;item&gt;Party&lt;/item&gt;<br />
    &lt;/string-array&gt;<br />
&lt;/resources&gt;<br />

 

Step 6

Add the Error Message

We need to add the error messages in the /res/values/string.xml to display the an error message, when user enter incorrect data. Here is the list of error messages that we will be using in our app :

<br />
&lt;string name=&quot;nonEmpty&quot;&gt;Please, enter the filed&lt;/string&gt;<br />
&lt;string name=&quot;validation_name_length&quot;&gt;Please, enter the name with at least 3 characters&lt;/string&gt;<br />
&lt;string name=&quot;validation_participants&quot;&gt;Please, enter the number of participants&lt;/string&gt;<br />
&lt;string name=&quot;validation_valid_email&quot;&gt;Please, enter valid email address&lt;/string&gt;<br />
&lt;string name=&quot;validation_date&quot;&gt;Date must be in future&lt;/string&gt;<br />
&lt;string name=&quot;validation_type&quot;&gt;Please, select type&lt;/string&gt;<br />
&lt;string name=&quot;validation_success&quot;&gt;Validation succeeded! \nThat was easy, wasn\'t it?&lt;/string&gt;<br />
&lt;string name=&quot;count&quot;&gt;Please enter number only&lt;/string&gt;<br />
&lt;string name=&quot;min_number&quot;&gt;Please enter number greater than 5.5&lt;/string&gt;<br />

 

Step 7

Add Validation rules

Next, we need to add the validation rules on the EditText fields and Spinner. 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 the error message to display an error on the screen. These are the following Annotations defined in library to create validation rules :

  • @NotEmpty : Ensures that the field is not empty.
  • @MinLength : Define minimum length of the input string.
  • @RegExp : Define custom rules
  • @MinNumberValue : Define minimum number of input string
  • @MaxNumberValue : Define maximum number of input string

 

<br />
import eu.inmite.android.lib.validations.form.FormValidator;<br />
import eu.inmite.android.lib.validations.form.annotations.MinLength;<br />
import eu.inmite.android.lib.validations.form.annotations.MinNumberValue;<br />
import eu.inmite.android.lib.validations.form.annotations.MinValue;<br />
import eu.inmite.android.lib.validations.form.annotations.NotEmpty;<br />
import eu.inmite.android.lib.validations.form.annotations.RegExp;<br />
import eu.inmite.android.lib.validations.form.callback.SimpleErrorPopupCallback;<br />
import static eu.inmite.android.lib.validations.form.annotations.RegExp.EMAIL;</p>
<p>public class MainActivity extends AppCompatActivity {</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.nonEmpty, order = 1)</p>
<p>    // Checks whether the input string length is not smaller than 3 and its order number is 2<br />
    @MinLength(value = 3, messageId = R.string.validation_name_length, order = 2)<br />
    protected EditText name;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_valid_email, order = 3)</p>
<p>    // Define input should be email id, an error message and order number 4<br />
    @RegExp(value = EMAIL, messageId = R.string.validation_valid_email, order = 4)<br />
    protected EditText email;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(order = 5, messageId = R.string.nonEmpty)</p>
<p>    //Set minimum value is 1L and oder number is 6<br />
    @MinValue(value = 1L, messageId = R.string.validation_participants, order = 6)<br />
    protected EditText participants;</p>
<p>    // set minimum number of the input value is 5.5, set an error message and also add order number is 7<br />
    @MinNumberValue(value = &quot;5.5&quot;, messageId = R.string.min_number, order = 7)<br />
    protected EditText minValue;</p>
<p>    // set custom rule expression, set an error message and order number is 8<br />
    @RegExp(value = &quot;^[0-9]+$&quot;, messageId = R.string.count, order = 8)<br />
    protected EditText count;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_type,order = 9)<br />
    protected Spinner mSpinner;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);<br />
    }<br />
}<br />

 

Step 8

Initialize the Text Fields

We need to initialize the EditText in the MainActivity file to get the string entered by the user in text fields.

<br />
import eu.inmite.android.lib.validations.form.FormValidator;<br />
import eu.inmite.android.lib.validations.form.annotations.MinLength;<br />
import eu.inmite.android.lib.validations.form.annotations.MinNumberValue;<br />
import eu.inmite.android.lib.validations.form.annotations.MinValue;<br />
import eu.inmite.android.lib.validations.form.annotations.NotEmpty;<br />
import eu.inmite.android.lib.validations.form.annotations.RegExp;<br />
import eu.inmite.android.lib.validations.form.callback.SimpleErrorPopupCallback;<br />
import static eu.inmite.android.lib.validations.form.annotations.RegExp.EMAIL;</p>
<p>public class MainActivity extends AppCompatActivity {</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.nonEmpty, order = 1)</p>
<p>    // Checks whether the input string length is not smaller than 3 and its order number is 2<br />
    @MinLength(value = 3, messageId = R.string.validation_name_length, order = 2)<br />
    protected EditText name;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_valid_email, order = 3)</p>
<p>    // Define input should be email id, an error message and order bumber 4<br />
    @RegExp(value = EMAIL, messageId = R.string.validation_valid_email, order = 4)<br />
    protected EditText email;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(order = 5, messageId = R.string.nonEmpty)</p>
<p>    //Set minimum value is 1L and oder number is 6<br />
    @MinValue(value = 1L, messageId = R.string.validation_participants, order = 6)<br />
    protected EditText participants;</p>
<p>    // set minimum number of the input value is 5.5, set an error message and also add order number is 7<br />
    @MinNumberValue(value = &quot;5.5&quot;, messageId = R.string.min_number, order = 7)<br />
    protected EditText minValue;</p>
<p>    // set custom rule expression, set an error message and order number is 8<br />
    @RegExp(value = &quot;^[0-9]+$&quot;, messageId = R.string.count, order = 8)<br />
    protected EditText count;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_type,order = 9)<br />
    protected Spinner mSpinner;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        // Initialize the EditText by calling this method<br />
        initializeField();<br />
    }</p>
<p>   /**<br />
    * This method is used to Initialize the EditText<br />
    */<br />
    public void initializeField(){</p>
<p>        name = (EditText) findViewById(R.id.name);<br />
        participants = (EditText) findViewById(R.id.participants);<br />
        email = (EditText) findViewById(R.id.email);<br />
        mSpinner = (Spinner) findViewById(R.id.spinner);<br />
        minValue = (EditText) findViewById(R.id.min_number);<br />
        count = (EditText) findViewById(R.id.count_number);<br />
    }</p>
<p>}<br />

 

Step 9

Set an Array Adapter in the Spinner

To show drop down list in the spinner, we need to add the list of items to Spinner. So do so, we will use Array Adapter. Here is the sample code for the same :

<br />
import eu.inmite.android.lib.validations.form.FormValidator;<br />
import eu.inmite.android.lib.validations.form.annotations.MinLength;<br />
import eu.inmite.android.lib.validations.form.annotations.MinNumberValue;<br />
import eu.inmite.android.lib.validations.form.annotations.MinValue;<br />
import eu.inmite.android.lib.validations.form.annotations.NotEmpty;<br />
import eu.inmite.android.lib.validations.form.annotations.RegExp;<br />
import eu.inmite.android.lib.validations.form.callback.SimpleErrorPopupCallback;<br />
import static eu.inmite.android.lib.validations.form.annotations.RegExp.EMAIL;</p>
<p>public class MainActivity extends AppCompatActivity {</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.nonEmpty, order = 1)</p>
<p>    // Checks whether the input string length is not smaller than 3 and its order number is 2<br />
    @MinLength(value = 3, messageId = R.string.validation_name_length, order = 2)<br />
    protected EditText name;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_valid_email, order = 3)</p>
<p>    // Define input should be email id, an error message and order bumber 4<br />
    @RegExp(value = EMAIL, messageId = R.string.validation_valid_email, order = 4)<br />
    protected EditText email;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(order = 5, messageId = R.string.nonEmpty)</p>
<p>    //Set minimum value is 1L and oder number is 6<br />
    @MinValue(value = 1L, messageId = R.string.validation_participants, order = 6)<br />
    protected EditText participants;</p>
<p>    // set minimum number of the input value is 5.5, set an error message and also add order number is 7<br />
    @MinNumberValue(value = &quot;5.5&quot;, messageId = R.string.min_number, order = 7)<br />
    protected EditText minValue;</p>
<p>    // set custom rule expression, set an error message and order number is 8<br />
    @RegExp(value = &quot;^[0-9]+$&quot;, messageId = R.string.count, order = 8)<br />
    protected EditText count;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_type,order = 9)<br />
    protected Spinner mSpinner;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        // Initialize the EditText by calling this method<br />
        initializeField();<br />
    }</p>
<p>   /**<br />
    * In this method, Initialize the EditText<br />
    */<br />
    public void initializeField(){</p>
<p>        name = (EditText) findViewById(R.id.name);<br />
        participants = (EditText) findViewById(R.id.participants);<br />
        email = (EditText) findViewById(R.id.email);<br />
        mSpinner = (Spinner) findViewById(R.id.spinner);<br />
        minValue = (EditText) findViewById(R.id.min_number);<br />
        count = (EditText) findViewById(R.id.count_number);<br />
        // set the Adapter to the spinner<br />
        mSpinner.setAdapter(ArrayAdapter.createFromResource(this,<br />
              R.array.demo_types,<br />
              R.layout.support_simple_spinner_dropdown_item));<br />
    }</p>
<p>}<br />

 

Step 10

Validate the Form

Finally, we will validate the form on the click of submit button. So, create a validate() method and within this method, call the FormValidator.validate() method to apply the rules on form fields and display error messages in case rules are not satisfied.

<br />
import eu.inmite.android.lib.validations.form.FormValidator;<br />
import eu.inmite.android.lib.validations.form.annotations.MinLength;<br />
import eu.inmite.android.lib.validations.form.annotations.MinNumberValue;<br />
import eu.inmite.android.lib.validations.form.annotations.MinValue;<br />
import eu.inmite.android.lib.validations.form.annotations.NotEmpty;<br />
import eu.inmite.android.lib.validations.form.annotations.RegExp;<br />
import eu.inmite.android.lib.validations.form.callback.SimpleErrorPopupCallback;<br />
import static eu.inmite.android.lib.validations.form.annotations.RegExp.EMAIL;</p>
<p>public class MainActivity extends AppCompatActivity {</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.nonEmpty, order = 1)</p>
<p>    // Checks whether the input string length is not smaller than 3 and its order number is 2<br />
    @MinLength(value = 3, messageId = R.string.validation_name_length, order = 2)<br />
    protected EditText name;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_valid_email, order = 3)</p>
<p>    // Define input should be email id, an error message and order bumber 4<br />
    @RegExp(value = EMAIL, messageId = R.string.validation_valid_email, order = 4)<br />
    protected EditText email;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(order = 5, messageId = R.string.nonEmpty)</p>
<p>    //Set minimum value is 1L and oder number is 6<br />
    @MinValue(value = 1L, messageId = R.string.validation_participants, order = 6)<br />
    protected EditText participants;</p>
<p>    // set minimum number of the input value is 5.5, set an error message and also add order number is 7<br />
    @MinNumberValue(value = &quot;5.5&quot;, messageId = R.string.min_number, order = 7)<br />
    protected EditText minValue;</p>
<p>    // set custom rule expression, set an error message and order number is 8<br />
    @RegExp(value = &quot;^[0-9]+$&quot;, messageId = R.string.count, order = 8)<br />
    protected EditText count;</p>
<p>    // Ensures that the field is not empty.<br />
    @NotEmpty(messageId = R.string.validation_type,order = 9)<br />
    protected Spinner mSpinner;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);<br />
        initializeField();<br />
    }</p>
<p>   /**<br />
    * In this method, Initialize the EditText.<br />
    */<br />
    public void initializeField(){</p>
<p>        name = (EditText) findViewById(R.id.name);<br />
        participants = (EditText) findViewById(R.id.participants);<br />
        email = (EditText) findViewById(R.id.email);<br />
        mSpinner = (Spinner) findViewById(R.id.spinner);<br />
        minValue = (EditText) findViewById(R.id.min_number);<br />
        count = (EditText) findViewById(R.id.count_number);<br />
        // set the Adapter to the spinner<br />
        mSpinner.setAdapter(ArrayAdapter.createFromResource(this,<br />
              R.array.demo_types,<br />
              R.layout.support_simple_spinner_dropdown_item));<br />
    }</p>
<p>   /**<br />
    * Apply validation rule on the form by calling callback register method.<br />
    */<br />
    public void validate(View view) {<br />
        long start = SystemClock.elapsedRealtime();<br />
        final boolean isValid = FormValidator.validate(this,<br />
                         new SimpleErrorPopupCallback(this, true));<br />
        long time = SystemClock.elapsedRealtime() - start;<br />
        Log.e(getClass().getName(), &quot;validation finished in [ms] &quot; + time);</p>
<p>        if (isValid) {</p>
<p>            Toast.makeText(getApplicationContext(),&quot;Success&quot;, Toast.LENGTH_LONG).show();<br />
        }<br />
    }</p>
<p>}<br />

 

name_validation
 

name_validation1
 

email_validation
 

min_value_validation
 

spinner_validation
 

success
 

Udemy Generic 728x90

Spread the word. Share this post!