Saturday, 29 August 2015

Android Programming Tutorial 35 : EditText Validations In Android:

Edit Text Validations In ANDROID:

Create Android Application:

  • File >> New >> Android Application
  • Enter Project name: EditTextValidationApp
  • Package: com.ambilpursunil.newapp
  • Keep other default selections, click Next until you reach Finish

                                   

     1.Simply Copy and Past the Code which is display below in the  MainActivity.java 

    package com.ambilpursunil.newapp;

    import android.app.Activity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MainActivity extends Activity {
               
                private EditText etNormalText;
                private EditText etEmailText;
                private EditText etPhoneNumber;
                private Button btnSubmit;
               
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                registerViews();
                }
                private void registerViews() {
                etNormalText = (EditText) findViewById(R.id.et_Normal);
                etNormalText.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                Validation.hasText(etNormalText);
                }
                @Override
    public void onTextChanged(CharSequence s, int start, int count, int after) {
                }
                @Override
    public void beforeTextChanged(CharSequence s, int start, int before,int count) {
                }
                });
                etEmailText = (EditText) findViewById(R.id.et_Email);
                etEmailText.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                Validation.isEmailCheck(etEmailText, true);
                }
                @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
                @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
               int after) {
               }
               });
               etPhoneNumber = (EditText) findViewById(R.id.et_Phone);
               etPhoneNumber.addTextChangedListener(new TextWatcher() {
               @Override
               public void afterTextChanged(Editable s) {
               Validation.isPhoneNumber(etPhoneNumber, false);
               }
              @Override
     public void onTextChanged(CharSequence s, int start, int before, int count) {
              }
              @Override
     public void beforeTextChanged(CharSequence s, int start, int count,
              int after) {
              }
              });
              btnSubmit = (Button) findViewById(R.id.btn_Submit);
              btnSubmit.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View arg0) {
    /*Validation class will check the error and display the error on respective fields
    but it won't resist the form submission, so we need to check again before submit
    */
             if(checkValidation())
             submitForm();
             else
    Toast.makeText(MainActivity.this, "No Data Return Yet",                                                      Toast.LENGTH_LONG).show();
             }
      private void submitForm() {
    Toast.makeText(MainActivity.this, "Submitting form...", Toast.LENGTH_LONG).show();
               }
            private boolean checkValidation() {
            boolean ret = true;
            if(Validation.hasText(etNormalText)) ret = false;
            if(Validation.isEmailCheck(etEmailText, true)) ret = false;
            if(Validation.isPhoneNumber(etPhoneNumber, true)) ret = false;
            return ret;
            }
            });
            }
    }

     2.Create a Java Class by Src=>package=>New=>Java Class  Validation.java  Copy and Past the Code which is display below. 

    package com.ambilpursunil.newapp;

    import java.util.regex.Pattern;

    import android.widget.EditText;

    public class Validation {
               
                // Regular Expression
        // you can change the expression based on your need
     private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        private static final String PHONE_REGEX = "\\d{3}-\\d{7}";
       
        //Error Message
        private static final String EMAIL_MSG = "invalid mail";
        private static final String REQUIRED_MSG = "required";
        private static final String PHONE_MSG = "###-#######";

        //calling this method for E-mail
        public static boolean isEmailCheck(EditText editText, boolean required ){
                return isValid(editText,EMAIL_REGEX, EMAIL_MSG, required);
        }

        public static boolean isPhoneNumber(EditText editText, boolean required){
                return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
        }
       private static boolean isValid(EditText editText, String regex,
                                        String errMsg, boolean required) {
                String text = editText.getText().toString().trim();
                //clearing the error,if data is previously set
                editText.setError(null);
               
                // text required and editText is blank, so return false
                if(required && !hasText(editText))
                return false;
               
                //if pattern does not match then return false
                if(required && !Pattern.matches(regex, text)){
                editText.setError(null);
                return false;
                };
                return true;
                }
                public static boolean hasText(EditText editText) {
                String text = editText.getText().toString().trim();
                editText.setError(null);
                //Length zero mean there is no text
                if(text.length() == 0){
                editText.setError(REQUIRED_MSG);
                return false;
                }
                return true;
               }
       }


    3.Simple Copy and Past the below code:  actvitiy_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:id="@+id/et_Normal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Normal Text"
            android:textStyle="bold"
            android:textSize="20dp" />

        <EditText
            android:id="@+id/et_Email"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Email Text"
            android:textStyle="bold"
            android:textSize="20dp" />
       
        <EditText
            android:id="@+id/et_Phone"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:hint="Enter Email Text"
            android:textStyle="bold"
            android:textSize="20dp"
            android:inputType="number" />
        <Button
            android:id="@+id/btn_Submit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Submit" />

    </LinearLayout>

    4.Copy and past the code for manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.ambilpursunil.newapp"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="21" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

    5.Right click on the project and Run As-->Android Application


    OutPut:

    When our application launch it will display the 3 edit texts enter the data and verify.


    Please Send Your Comments To ambilpura.sunil@gmail.com   



    Stay Tune For Next Tutorial...  Toast Validations In Android:


    No comments:

    Post a Comment