I want to validate an email with a regex. And the code following shows the regular expression that I've used. The form however does not accept a simple [email protected]. (anystring is an alphabetic).
Am I missing out something?
window.onload = function () {
document.getElementById("form").onsubmit = validate;
}
function validate() {
var email = document.getElementsByTagName("input")[6].value;
var regex = /^\w@\w+\.\w$/;
if (!regex.test(email)) {
alert("enter a valid email");
return false;
} else return true;
}
Unless you know for sure that email addresses entered will match that format, you should consider using a regular expression that matches more.
"()<>[]:,;@\"!#$%&'*+-/=?^_`{}| ~.a"@üñîçøðé.com is technically(!) a correct email address. While it may not be a good idea to match all of this craziness, this may be what you are looking for and will match the vast majority of email addresses today:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Again, if you are sure your email addresses will be in the format you were going for originally, go with Valinho's answer.
An interesting read about matching email addressses with regular expressions (contains the above regex): http://www.regular-expressions.info/email.html
And the official standard (without unicode madness): https://www.rfc-editor.org/rfc/rfc5322
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