纯javascript验证

时间:2011-11-26 13:27:09

标签: javascript

我厌倦了做有效的电子邮件和必要的字段验证但是使用这个功能我做的女巫我只想用纯JavaScript做它只保持显示所需的em

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JS valdation</title>
    <script type="text/javascript">
        function validateForm() {
            var email = document.getElementById('emailaddress');
            var name = document.getElementById('username');
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (email.value == "" || name.value == "") {
                document.getElementById("required").style.display = "block";
                document.getElementById("required_email").style.display = "block";
                document.getElementById("valide_email").style.display = "none";
            }
            else if(!filter.test(email.value)) {
                document.getElementById("valide_email").style.display = "block";
                document.getElementById("required").style.display = "none";
            }
            return false;
        }
    </script>
</head>
<body>
<form name="myForm" action="" onsubmit="return validateForm();" method="post">
Email: <input id="emailaddress" type="text" name="email">
<input type="submit" value="Submit">
<em id="valide_email" style="display:none">please enter a valid email ex:(user@user.com)</em>
<em id="required_email" style="display:none">this filed is required</em>
First name: <input id="username" type="text" name="fname">
<em id="required" style="display:none">this filed is required</em>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

在你的Css样式表中添加这两个类(或作为Id的)

#valide_email.visible, #required_email.visible {
    visibility:hidden; /*or display: none or whatever*/
}
#valide_email.hidden, #required_email.hidden {
    visibility:visible;
}

在您的javascript中,您可以在隐藏和可见之间更改其类:

else if(!filter.test(email.value)) {
     document.getElementById("valide_email").className = "visible";
     document.getElementById("required").className = "hidden";
}