Reputation: 622
I am trying to validate an email address. I currently have:
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,})$";
This will validate any email but I am trying to validate only a company specific email e.g.
The email will always end with .com but i would like the ability to change the company name at a later date with a different specific string e.g. @anotheremail.com, @somethingelse.com
Can anyone help with with the syntax?
Thanks
Upvotes: 2
Views: 3524
Reputation: 443
I am using this is for specific ending domain. Simply replace your ending domain with "@gmail.com"
private static final String EMAIL_REGEX1 =
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@gmail.com";
private static final String EMAIL_REGEX1 =
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@somethingelse.com";
Visit https://ideone.com/UUTnky for Full Regex Email Validation Java Implementation.
Upvotes: 0
Reputation: 785156
You can validate company specific email using this regex:
private static final String coDomain = "specificemail.com";
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ Pattern.quote(coDomain) + "$";
Later on just change the value of coDomain variable to some other name as needed.
Upvotes: 2
Reputation: 14949
Perhaps something like this:
public static Pattern getEmailValidator( String domain ) {
return Pattern.compile( "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + domain );
}
public void someMethodThatNeedsToValidatEmail( String domain, String email ) {
return getEmailValidator( domain ).matches( email );
}
Note, this is untested code...
Upvotes: 0
Reputation: 37813
// be careful with regex meta characters in the company name.
public static String emailFromCompanyPatternString(String company) {
return "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ company + (\\.[A-Za-z]{2,})$";
}
Upvotes: 0