前端jquery---表单验证

重点:

  1、表单的提交

  2、触发blur事件

  3、判断是否正确,提交与否 return False

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<form action="http://localhost/reg">
    <p>
        用户名:
    </p>
    <p>
        <input type="text" name="username" id="username" >
        <span id="username_error"></span>
    </p>
     <p>
        密码:
    </p>
    <p>
        <input type="text" name="pwd" id="pwd">
        <span id="pwd_error"></span>

    </p>
    <p>
        确认密码:
    </p>
    <p>
        <input type="text" name="repwd" id="repwd">
        <span id="repwd_error"></span>
    </p>
    <input type="submit" value="提交" />
</form>


<script src="jquery.js"></script>

<script>


    $("form").submit(function () {

        $("input[type='text']").trigger('blur');

        total = 0;
        $("input[type='text']").each(function () {
//            total += parseInt($(this).attr("s"));
            total += $(this).data("s");
        });

        console.log(total);
        if(total != 3){
            return false;
        }

    });


    $("#username").blur(function () {
        var username = $(this).val();
        if(username.length < 6){
            $(this).data({"s":0});
            $("#username_error").text("用户名小于6位").css({"color":"red"});
        }else{
            $(this).data({"s":1});
            $("#username_error").text("");
        }
    });

    $("#pwd").blur(function () {
        var pwd = $(this).val();
        if(pwd.length < 8){
            $(this).data({"s":0});
            $("#pwd_error").text("密码小于8位").css({"color":"red"});
        }else{
            $(this).data({"s":1});
            $("#pwd_error").text("");
        }
    });


    $("#repwd").blur(function () {
        var pwd = $("#pwd").val();
        var repwd = $(this).val();
        if(pwd != repwd){
            $(this).data({"s":0});
            $("#repwd_error").text("两次密码不一致").css({"color":"red"});
        }else{
            $(this).data({"s":1});
            $("#repwd_error").text("");
        }
    });

</script>

</body>
</html>
原文地址:https://www.cnblogs.com/di2wu/p/10035789.html