Reputation: 23
How can I restrict only numerics in the Email address. I tried below and it didn't work. My email should accept Alpha-numerics, dot, hyphen and underscore followed by "@AnyDomain.com". But it should not accept only numerics like "[email protected]"
Pattern regexPattern = Pattern.compile("^[(a-zA-Z0-9-\\_\\.!\\D)]+@[(a-zA-Z)]+\\.[(a-zA-Z)]{2,3}$");
Matcher regmatcher = regexPattern.matcher(email);
Upvotes: 2
Views: 2228
Reputation: 6273
The regex below works for me every time for email verification. However, this might not solve all cases as emails accept a whole range of characters and more recently, different formats. If you're using the email for authentication, I would advise you send a verification email to confirm or add an extra mode of authentication.
/^[a-zA-Z.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
Basically, the strength of a validation regex lies in the number of cases it can accurately capture while simultaneously checking for non-compliance (fakes). Each of these character sequences has a purpose in the overall validation process. You can learn more about regular expressions here.
Upvotes: 0
Reputation: 16214
Using regex for email can be problematic. Emails are not as simple as you think - there are many valid characters. Ideally you should let the browser do it input[type="email"]
and send your users an activation email in order to prove that the email address is valid but I understand that there may be a legitimate need to validate the address on the server.
There's useful info here: https://stackoverflow.com/a/201378/1921385
Still need an rx?
According to https://emailregex.com/ the regex used by W3C to validate an input[type=email]
is:
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
So you could use this and just take out the number portion:
/^[a-zA-Z.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
Have a play at regex101.com
Here's a demo:
input {border:10px solid red;}
input:valid {border-color:green;}
<input type="text" required="required" pattern="^[a-zA-Z.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$" placeholder="type=text, using a pattern" />
<input type="email" required="required" placeholder="type=email, no pattern here" />
Upvotes: 0
Reputation: 5726
I have modified regex the one provided in the question.
[a-zA-Z]+[(a-zA-Z0-9-\\_\\.!\\D)]*[(a-zA-Z0-9)]+@[(a-zA-Z)]+\.[(a-zA-Z)]{2,3}
I have added [a-zA-Z]+ at the beginning to ensure the email address doesn't start with numbers. If the email address can start with the special symbol, make sure you update it in the first block.
Upvotes: 0