6

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 "example@gmail.com.com" also, the response i'm getting as true.

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

Steve Benett
  • 12,843
  • 7
  • 59
  • 79
Gowri
  • 502
  • 2
  • 4
  • 10

9 Answers9

32

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();

}
Serhii Nadolynskyi
  • 5,473
  • 3
  • 21
  • 20
WISHY
  • 11,067
  • 25
  • 105
  • 197
1

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

Richa
  • 3,165
  • 1
  • 22
  • 26
0

Use the following class:

public class RequiredFieldValidator implements Validator {

    /** The objects. */
    List<EditText> objects;

    /** The Constant EMAIL_ADDRESS_PATTERN. */
    private final static 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}" + ")+");

    /**
     * Check email.
     *
     * @param email the email
     * @return true, if successful
     */
    public static boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }

    /**
     * Instantiates a new required field validator.
     *
     * @param objects the objects
     */
    public RequiredFieldValidator(List<EditText> objects) {
        this.objects = objects;
    }

    /* (non-Javadoc)
     * @see com.gangaz.mobi.supermarket.helper.Validator#setFailureMessage(java.lang.String)
     */
    @Override
    public void setFailureMessage(String message) {
        // TODO Auto-generated method stub

    }

    /* (non-Javadoc)
     * @see com.gangaz.mobi.supermarket.helper.Validator#setType(int)
     */
    @Override
    public void setType(int type) {
        // TODO Auto-generated method stub

    }

    /* (non-Javadoc)
     * @see com.gangaz.mobi.supermarket.helper.Validator#validate()
     */
    @Override
    public boolean validate() {
        boolean valid = false;
        for (EditText obj : objects) {

            if (obj.getText().toString().trim().length() == 0) {
                valid = false;
                break;
            }

        }
        return valid;
    }
}

Then in your activity do this:

if (email.length() != 0 && 
  RequiredFieldValidator.checkEmail(email.trim()) != true) {

                //show toast for invalid email

                }
Snehal Poyrekar
  • 735
  • 5
  • 17
0

Initialize pattern as below

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}" + ")+");

copy below function to you activity

private boolean checkEmail(String email1) {
        return EMAIL_ADDRESS_PATTERN.matcher(email1).matches();
    }

And call this function with email edittext String. This function write TRUE or FALSE as a result

Dhaval Patel
  • 694
  • 4
  • 12
0

Use:

  public boolean validateEmail(String strEmail) {
            Matcher matcher;
            String EMAIL_PATTERN = "[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}" + ")+";
            Pattern pattern = Pattern.compile(EMAIL_PATTERN);
            matcher = pattern.matcher(strEmail);
            return matcher.matches();

If it returns true then email is valid else not.

Rishabh Srivastava
  • 3,683
  • 2
  • 30
  • 58
0

Below is the easiest and best way we should handle it,

EditText e1 = (EditText)findViewById(R.id.e1); 
TextView t1 = (TextView)findViewById(R.id.t1); 

String email = e1.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

// Below is the code that goes on your button click
if (email.matches(emailPattern))
{
    // Do what you want to, Allow user to next screen
}
else 
{
    // Show error Message
}
User0911
  • 1,552
  • 5
  • 22
  • 33
  • You can have a idea from the link, http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ – User0911 Sep 20 '13 at 06:00
0

try with:

String emailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Lele
  • 703
  • 3
  • 15
  • 34
  • You should add some context as to why this answer works. Otherwise, its very short and prone to deletion. –  Sep 20 '13 at 06:21
  • This won't work..An email is valid if we can send a mail to it.Even `space`,`*`,`%` and many other chars are valid in an email id – Anirudha Sep 20 '13 at 08:18
  • i'I don't have adding a context, because, in her code there're just an email_pattern – Lele Sep 20 '13 at 20:29
0

try this...

public static boolean validateEmail(String email)
{
    boolean isValid = false;

    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;

    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if(matcher.matches()) 
    {
        isValid = true;
    }

    return isValid;
}
Anil kumar
  • 1,534
  • 3
  • 14
  • 20
  • That has been propagated on a few sites, but is bad because IT DOESN'T ALLOW A TLD LONGER THAN 4 CHARACTERS! – androidguy May 10 '17 at 01:41
0

try this

   private boolean validEmail(String email) 
   {
     // TODO Auto-generated method stub
     String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
     String emailPatternnew = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+\\.+[a-z]+";
     String domain = email.substring(email.indexOf('@'), email.length());
     String last = domain.substring(domain.indexOf('.'),domain.length());
     if (email.matches(emailPattern) && (last.length() ==3 || last.length() == 4)) // check @domain.nl or @domain.com or @domain.org
    {      
        return true;
    }
    else if(email.matches(emailPatternnew) && last.length() == 6 && email.charAt(email.length()-3)== '.') //check for @domain.co.in or @domain.co.uk
    {
        return true;
    }
    else
    {
        return false;
    }
}
swati srivastav
  • 635
  • 4
  • 15
  • This won't work..An email is valid if we can send a mail to it.Even `space`,`*`,`%` and many other chars are valid in an email id – Anirudha Sep 20 '13 at 08:16