Pages

Monday, July 23, 2012

Email validation in ANDROID.

This is a simple example showing email validation in ANDROID.
This example uses regex for email validation.
Create a button and an edittext in your main.xml file and try this code.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.coderzheaven;
 
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class EmailValidationDemo extends Activity   {
 
    EditText TF;
    public Button checkButton;
 
    public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
              "[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}" +
              ")+"
          );
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
 
       TF=(EditText) findViewById(R.id.TF);
       checkButton=(Button) findViewById(R.id.checkButton);
 
        checkButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
               String email=TF.getText().toString();
               if(checkEmail(email))
                  Toast.makeText(EmailValidationDemo.this,"Valid Email Addresss", Toast.LENGTH_SHORT).show();
               else
                  Toast.makeText(EmailValidationDemo.this,"Invalid Email Addresss", Toast.LENGTH_SHORT).show();
        }
        });
    }
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
}

2 comments:

Popular Posts