Sunday, 18 March 2012

Email Validation in Android



Email_ValidationActivity.java
package com.Email_Validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Email_ValidationActivity extends Activity {

    EditText TextEmail;
    String emailString;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextEmail = (EditText) findViewById(R.id.txtEmail);
    }

    String regEx = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
            + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
            + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";

    public void btnValidateEmailAddress(View v) {
        emailString = TextEmail.getText().toString().trim();

        Matcher matcherObj = Pattern.compile(regEx).matcher(emailString);

        if (matcherObj.matches()) {
            //Toast.makeText(v.getContext(), emailString + " is valid",Toast.LENGTH_SHORT).show();
            showAlert(emailString + " is valid", v.getContext());
        } else {
            //Toast.makeText(v.getContext(), emailString + " is InValid",Toast.LENGTH_SHORT).show();
            showAlert(emailString + " is InValid", v.getContext());
        }
    }
   
    // For alert message

        public static void showAlert(String msg, Context context) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage(msg).setPositiveButton("Ok", dialogClickListener)
                    .show();
        }

        static DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    // Yes button clicked

                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    // No button clicked
                    break;
                }
            }
        };

}


Layout : main.xml

No comments:

Post a Comment