RegEx Not Recognizing Invalid Email
I am trying to validate an email address for a form element. I am familiar with regular expressions so I believe that part is correct, but I want it to display an alert when the email entered is invalid. My problem is that the form submits even when I enter an invalid email address instead of popping up the alert window.
RegEx function in javascript:
function validateEmail()
{
var myEmailRegEx = /w+@w+.[a-z]|[A-Z]|d|.|-{2,}/
if(myEmailRegEx.test(document.getElementById("EmailAddress")))
{
return true;
}
else
{
alert("That is not a valid email address");
return false;
}
}
form HTML:
<input type="text" name="Email" id="EmailAddress" size="50" />
<br />
<input type="submit" value="Submit Email" onClick="validateEmail();" />
Just for the sake of clarity, the problem with what you were doing was that you were giving an object to the regex for testing, which always returns true(weird though). With the .value we get the string that the field holds and then test the regex against it.
you should use,
var myEmailRegEx = new RegExp("/w+@w+.[a-z]|[A-Z]|d|.|-{2,}")
myEmailRegEx.test(document.getElementById("EmailAddress").value)
Suppose that email address is present in a form with id = "my_form". To prevent the default submission of that form, you would use
$("#my_form").preventDefault();
if the email turns out to be true, you could then submit the form.
if(myEmailRegEx.test(document.getElementById("EmailAddress").value)){
document.getElementById("mu_form").submit();
}
that should be it. I hope you have an idea where to plug in these code snippets :-)
Could just do:
<input type="email" />
and be done with it.
Try using an onchange
event on the input field contain the email. For example:
<input type="text" name="Email" id="EmailAddress" size="50" onchange="validateEmail();" />
<br />
<input type="submit" value="Submit Email"/>
The above approach will call your validateEmail
function whenever the value changes in that field.
上一篇: 为什么我的Javascript正则表达式输出不一致?
下一篇: RegEx无法识别无效的电子邮件