Email validation using regex
The Email Id such as adam.sandler@findnerd.com is made up of local-part, an @ symbol and then a domain part.
Hence, Email Id is of the form : local_part@domain
*TLD = Top Level Domain
- Some Valid Emails
- findnerd@yahoo.com, findnerd-100@yahoo.com, findnerd.100@yahoo.com
- findnerd222@mkyong.com, findnerd.100@findnerd .com.au
- findnerd@1.com, findnerd@gmail.com.com
- findnerd+100@gmail.com, findnerd-100@yahoo-test.com
- Some Invalid Emails
- findnerd must contains @ symbol
- findnerd@.com.my tld can not start with dot .
- findnerd123@gmail.a .a is not a valid tld, last tld must contains at least two characters
- findnerd 123@.com tld can not start with dot .
- findnerd 123@.com.com tld can not start with dot .
- .findnerd @findnerd .com emails first character can not start with dot .
- findnerd()*@gmail.com emails is only allow character, digit, underscore and dash
- findnerd@%*.com emails tld is only allow character and digit
- findnerd..2002@gmail.com double dots . are not allow
- findnerd.@gmail.com emails last character can not end with dot .
- findnerd@findnerd@gmail.com double @ is not allow
- findnerd@gmail.com.1a -emails tld which has two characters can not contains digit
Here is the Class which validates Email Id using regex:
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* @param email
* hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String email) {
matcher = pattern.matcher(email);
return matcher.matches();
}
}
And in your Class you can validate the Email like this:
String emailID = findnerd@.gmail.com; // It is a invalid email
EmailValidator emailValidator = new EmailValidator();
if(emailValidator.validate(emailID)){
{
// Email is valid, do something
}
else{
// Email is invalid, do something
}
0 Comment(s)