Validate HTML form input with JavaScript
Possible Duplicate:
Validate email address in Javascript?
I have an HTML form that uses PHP/MySQL to post to a database. In the email section of the form, I want the user to be displayed an error message if he or she types in an email address that is not in valid email address format. I am modeling off of a code like this, but I cannot get it work.
Note that whenever I hit the submit button on the form, the form submits, and the PHP action works fine. The problem is I can enter anything I like in the form and it will pass fine. I would like for it to display the error message "Not a valid email address". I understand I can validate via PHP too, but I would like to validate on the client side as well.
Can anyone assist?
<script type="text/javascript">
function validateEmail()
{
var x=document.forms["test"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
<form name"test" action="roads.php" onsubmit="return validateEmail();" method="post">
<input type="text" name="email" placeholder="Enter your e-mail" />
<input type="submit" value="Show Me!" />
</form>
you are missing a =
in html, which doesn't make to form name test..and javascript can't find the form of name test, and throws error...check console log for javascript errors..
<form name"test" action="roads.php" onsubmit="return validateEmail();" method="post">
<form name="test" action="roads.php" onsubmit="return validateEmail();" method="post">
Working code
Here is a better way to access the form and its fields - also remember to return true
Assuming <form id="testform" action="roads.php" method="post">
we can use unobtrusive scripting
<script>
window.onload=function() {
document.getElementById("testform").onsubmit=function () {
var email=this.email.value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
}
}
</script>
链接地址: http://www.djcxy.com/p/16514.html
上一篇: 正则表达式验证电子邮件的意外行为