Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Email validation [duplicate]

Tags:

regex

android

How to do email validation? I have used following code to check validation for email.

final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-    Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(string);

The above code works fine, but if I enter the string as "[email protected]" also, the response i'm getting as true.

I need to validate this. How can I validate this?. Please help me.

like image 891
Gowri Avatar asked Sep 20 '13 05:09

Gowri


2 Answers

Use this block of code Pass the email to this function it will return a boolean value of either true or false

  private boolean validEmail(String email) {
    Pattern pattern = Patterns.EMAIL_ADDRESS;
    return pattern.matcher(email).matches();
}


  if (!validEmail(email)) {
     Toast.makeText(YourActivity.this,"Enter valid e-mail!",Toast.LENGTH_LONG).show();

}
like image 145
WISHY Avatar answered Nov 19 '22 16:11

WISHY


U dont need to define any reg because android itself giving functionality to check email is valid is not by TextUtils.isEmpty(edtEmail.getText().toString().trim())

second way is :

public static boolean isEmailValid(String email) {

        String regExpn = "^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
                + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
                + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
                + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
        CharSequence inputStr = email;
        Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches())
            return true;
        else
            return false;
    }

hope it help u

like image 25
Richa Avatar answered Nov 19 '22 16:11

Richa