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 anystring@anystring.anystring. (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;
}
Answer
With your currently setted regular expression your are only aceppting one char at the beginning and one char at the end. A valid email for your regex would be for example a@test.a
But you dont want that so change it to: var regex = /^\w+@\w+\.\w{2,3}$/;
You missed the plus char which means that you can enter at least one or more chars. The top level domain usually consists of two or three chars so you can limit it.
Now it should work.
No comments:
Post a Comment