Tuesday, March 20, 2012

How to validate EmailId field in Android?


We use regular expressions along with Pattern & Matcher classes and their methods to validate email address

Required regular expression is  as below:

String regExpn = m:val="0"m:val="0"m:val="centerGroup"m:val="1440"m:val="subSup"m:val="undOvr"
"^(([\\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})$";

Validation code goes as below:

private Boolean isValidEmail(String inputEmail)
{
      Pattern patternObj = Pattern.compile(regExpn);

      Matcher matcherObj = patternObj.matcher(inputEmail/*May be fetched from  EditText. This string is the one which you wanna validate for email*/);
            if (matcherObj.matches())
            {
                  //Valid email id…
                  return true;
}
            Else
{
//not a valid email id…
                  return false;
}
}


Happy coding:-)

No comments:

Post a Comment