表单验证功能

来源:互联网 发布:香港永久免费php空间 编辑:程序博客网 时间:2024/05/18 02:48
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        table {
            width: 700px;
        }
        td:first-child {
            width: 60px;
        }
        td:nth-child(2) {
            width: 200px;
        }
        td span {
            color: red;
        }
        .vali_Info {
            display: none;
        }
        .txt_focus {
            border-top: 2px solid black;
            border-left: 2px solid black;
        }
        .vali_success, .vali_fail {
            background: no-repeat left center;
            display:block;
        }
        /* 验证消息:验证通过时的样式 */
        .vali_success{
            background-image:url("images/ok.png");
            padding-left:20px;
            width:0;
            height:20px;
            overflow:hidden;
        }
        /* 验证消息:验证失败时的样式 */
        .vali_fail{
            background-image:url("images/warning.png");
            border:1px solid red;
            background-color:#ddd;
            color:Red;
            padding-left:30px;
        }
    </style>
</head>
<body>
<form id="form1">
    <h2>增加管理员</h2>
    <table>
        <tr>
            <td>姓名:</td>
            <td>
                <input type="text" name="username"/>
                <span>*</span>
            </td>
            <td>
                <div class="vali_Info">10个字符以内的字母、数字或下划线的组合</div>
            </td>
        </tr>
        <tr>
            <td>密码:</td>
            <td>
                <input type="password" name="pwd"/>
                <span>*</span>
            </td>
            <td>
                <div class="vali_Info">6位数字</div>
            </td>
        </tr>
        <tr>
            <td></td>
            <td colspan="2">
                <input type="submit" value="保存"/>
                <input type="reset" value="重填"/>
            </td>
        </tr>
    </table>
</form>
<script>
    var txtName = document.getElementsByName("username")[0];
    txtName.onfocus = getFocus;


    txtName.onblur = function () {
        vali(this, /^\w{1,10}$/);
    };
    var txtPwd = document.getElementsByName("pwd")[0];
    txtPwd.onfocus = getFocus;
    txtPwd.onblur = function () {
        vali(this, /^\d{6}$/)

    };


    function getFocus() {  // this --> txtName
        this.className = "txt_focus";
        this.parentNode.nextElementSibling.firstElementChild.className = "";

    }


    function vali(txt, reg) {
        txt.className = "";
        var div = txt.parentNode.nextElementSibling.firstElementChild;
        if (reg.test(txt.value)) {
            div.className = "vali_success";
        } else {
            div.className = "vali_fail";
        }
    }
</script>
</body>
</html>
原创粉丝点击