Is the following function ok to validate an email?
Just tested this function to validate an email..However,it does not validate the presence or absence of the dot in the email..Why this is happening and how can I fix this?
<script type="text/javascript">
function isEmail(textbox){
var reg4 =/^(\w+)@(\w+).(\w+)$/;
开发者_如何学运维 if(reg4.test(textbox.value)){
return true;
}
return false;
}
</script>
No, it's insufficient.
In particular, it doesn't handle all these (legal) variants:
quoted user parts, e.g. "my name"@example.com
Internationalised domain names (IDNs)
Domains with more than two labels
Domains with only one label (yes, those are legal)
Hyphens in domain names
user@[1.2.3.4]
Validating an e-mail address via a regexp is very hard. See section 3.4.1 of RFC 5322 for the formal syntax definition.
Do not use a regular expression to validate email addresses. Email addresses can include a lot of things you wouldn't imagine (like spaces), and it's more likely that the user will accidentally enter an invalid email address than an invalid one. Just check if there's an @
then send a confirmation email if you want.
From an answer to a related question:
There is no good (and realistic, see the fully RFC 822 compliant regex) regular expression for this problem. The grammar (specified in RFC 5322) is too complicated for that. Use a real parser or, better, validate by trying (to send a message).
the dot has a meaning in a regex
use [\.]
instead of .
You need to escape the dot, which normally matches any character.
var reg4 =/^(\w+)@(\w+)\.(\w+)$/;
Escape the dot with backslash: \.
. However, your regex would not be very good afterwards as it will not accept multiple dots in post-@ part, such as domain foo.co.uk
.
All in all, I'd advise againts using regexes to validate emails as they tend to get overcomplicated ;-) Simply check for presence of @ followed by a dot, or use a similarly lenient algorithm.
精彩评论