I'm new to Android developing. In my login authentication activity, I want validation for input fields. I want the characters after "." to be letters only.
ehsan@gmail. com
If user typed a String like this: ehsan@gmail.23 return false and make a Toast. my code is:
String email = "ehsan@gmail.com";
String[] ar = email.split(".");
if ( !ar[ar.length -1].matches("[a-z]") ){
Toast.makeText(getApplicationContext(), "your email is invalid", Toast.LENGTH_LONG).show();
return false; }
When I run this code, the app force closes. What is wrong?
Please use the Patterns
class to validate the email address:
public static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
I'm not complitely sure, but I suppose that problem is character @, its not in az interval. Hence, try
!ar[ar.length -1].matches("[a-z@]")
Also, keep in mind that e-mail could contain other special characters as '_' for example
email.matches(".+\\\\.[a-zA-Z]+")
seems to do the job. It's not the most sophisticated regex in the world, but it works.
valid@gmail.com
matches. invalid@gmail.a1b
doesn't match.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.