Amardeepvijay
Amardeepvijay

Reputation: 1628

Email Validation inside EditText

I want to validate an email introduced inside an EditText and this the code that I already have :

public static boolean isValidEmail(String str) {
    boolean isValid = false;
    String expression = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    CharSequence inputStr = str;
    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        isValid = true;
    }
    return isValid;
}

The problem is that when I am using _ and - these characters in starting of email id, no error is showing, but when i use any other character, an error is shown.

Now i want that when ever i used any special character in starting of email id, an error must be shown. no special character should be allowed in starting of email id.

what should i do for this..?

Upvotes: 0

Views: 187

Answers (3)

Nasz Njoka Sr.
Nasz Njoka Sr.

Reputation: 1118

Simply you can create a method and check it before accepting the input . There's no need for manual check of the email input characters android has all these data types defined you just need to call it Example

public static boolean isEmailValid(CharSequence email)
    { 
        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() ; 

    } 

Then on the oncreate or if within the button etc just call it like

 EditText et = (EditText)findViewbyid(R.id.email) ;
 String em = et.getText().toString() ;
 if(!Validating.isEmailValid(em))
      {
         et.setHint("use this format [email protected]") ;
          return;
      } 

Upvotes: 0

Siruk Viktor
Siruk Viktor

Reputation: 514

try this simple code:

    public static boolean validateEmailAddress(String emailAddress) {    
        regexPattern = Pattern .compile("^[(a-zA-Z-0-9-\\_\\+\\.)]+@[(a-z-A-z)]+\\.[(a-zA-z)]{2,3}$");
        regMatcher = regexPattern.matcher(emailAddress);
        if (regMatcher.matches())
            {
            return true;
        } else {
            return false;
        }
      }

Upvotes: 1

Blackbelt
Blackbelt

Reputation: 157457

The pattern used to validate an email address in the android sdk is

    public static final Pattern EMAIL_ADDRESS
        = 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}" +
            ")+"
        );

you can access it this way:

 android.util.Patterns.EMAIL_ADDRESS

Upvotes: 1

Related Questions