表单验证

表单验证:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>

<form action="test.html" method="get">
    <div>用户名:<input type="text" name="uid" id="uid" /></div>
    <div>密码:<input type="text" name="pwd1" id="pwd1" /></div>
    <div>确认密码:<input type="text" name="pwd2" id="pwd2" /></div>
    <div>邮箱:<input type="text" name="email" id="email" /></div>
    <div>年龄:<input type="text" name="nl" id="nl" /></div>
    <input type="submit" value="注册" onclick="return check()" />
</form>

</body>
<script type="text/javascript">

var uid = document.getElementById("uid");
var pwd1 = document.getElementById("pwd1");
var pwd2 = document.getElementById("pwd2");
var email = document.getElementById("email");
var nl = document.getElementById("nl")
    //非空验证
function check(){
    if(uid.value==""){
        alert("用户名不能为空");
        return false;
    }
    //相等验证
    if(pwd1.value!=pwd2.value){
        alert("两次输入的密码不相同!");
        return false;
    }
    //范围验证
    if(nl.value>=18 && nl.value<=50){
        alert("通过");
    }else{
        alert("年龄不在范围内");
        return false;
    }
    //正则验证
    var reg = /^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/;
    if(email.value.match(reg)==null){
        alert("邮箱输入不正确!");
        return false;
    }
}
</script>
</html>

效果图:

原文地址:https://www.cnblogs.com/Whitehat/p/8177933.html