I am using the follwoing regular expression
(".+@.+\\.[a-z]+")
Bit it accepts #@#.com as a valid email. What's the pattern I should use?
To get a valid email id we use a regular expression /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.
Regex : ^(.+)@(.+)$ This one is simplest and only cares about '@' symbol. Before and after '@' symbol, there can be any number of characters. Let's see a quick example to see what I mean.
[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times. @ matches itself.
You should use apache-commons email validator. You can get the jar file from here.
Here is a simple example of how to use it:
import org.apache.commons.validator.routines.EmailValidator;
boolean isValidEmail = EmailValidator.getInstance().isValid(emailAddress);
Here's a web page that explains that better than I can: http://www.regular-expressions.info/email.html (EDIT: that appears to be a bit out of date since it refers to RFC 2822, which has been superseded by RFC 5322)
And another with an interesting take on the problem of validation: http://www.markussipila.info/pub/emailvalidator.php
Generally the best strategy for validating an email address is to just try sending mail to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With