正在阅读:

Javascript表单验证案例

2,279

今天群里一朋友求助关于表单验证的小案例,自己也看了一点点js,但是一直没有写过,就帮她写了一把,技术不行呀,费了老大劲才弄出来,记录一下。

案例要求:

1.4个输入是否为空

2.老密码和新密码不能相同

3.两次新密码必须相同

4.输入的账户、新、旧密码长度不能小于3 大于8

5.每个框第一个输入的字符 不能是空格

javascript

HTML表单:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <meta http-equiv="content-language" content="zh-CN"/>
    <title>输入验证 BY:waitalone.cn</title>
</head>
<body>
<form id="form1" action="check.php" method="post">
    username: <input type="text" name="username"/><br/>
    oldpass: <input type="text" name="oldpass"/><br/>
    newpass: <input type="text" name="newpass"/><br/>
    renewpass: <input type="text" name="renewpass"/><br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

最终完成后的代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <meta http-equiv="content-language" content="zh-CN"/>
    <title>输入验证 BY:waitalone.cn</title>
</head>
<body>
<form id="form1" action="check.php" method="post" onsubmit="return check()">
    username: <input type="text" name="username"/><br/>
    oldpass: <input type="text" name="oldpass"/><br/>
    newpass: <input type="text" name="newpass"/><br/>
    renewpass: <input type="text" name="renewpass"/><br/>
    <input type="submit" value="提交"/>
</form>
<script type="text/javascript">
    function check() {
        var fm = document.getElementById('form1');
        var username = fm.username.value;
        var oldpass = fm.oldpass.value;
        var newpass = fm.newpass.value;
        var renewpass = fm.renewpass.value;
        if (username == "" || oldpass == "" || newpass == "" || renewpass == "") {
            alert("输入不能为空");
            return false;
        }
        if (oldpass == newpass) {
            alert("旧密码和新密码不能相等");
            return false;
        }
        if (newpass != renewpass) {
            alert("两次新密码必须相同");
            return false;
        }
        if ((username.length < 3 || username.length > 8) || (oldpass.length < 3 || oldpass.length > 8) || (newpass.length < 3 || newpass.length > 8)) {
            alert('用户名以及密码长度必须大于3且小于8');
            return false;
        }
        if (username.substr(0,1) == " " || oldpass.substr(0,1) == " " || newpass.substr(0,1) == " " || renewpass.substr(0,1) == " ") {
            alert("第一个字符不能为空格");
            return false;
        }
    }
</script>
</body>
</html>

留下脚印,证明你来过。

*

*

流汗坏笑撇嘴大兵流泪发呆抠鼻吓到偷笑得意呲牙亲亲疑问调皮可爱白眼难过愤怒惊讶鼓掌