0712-2888027 189-8648-0214
微信公眾號

孝感風信網(wǎng)絡(luò)科技有限公司微信公眾號

當前位置:主頁 > 技術(shù)支持 > Javascript/JQuery > JQuery Validate驗證插件的使用代碼示例

JQuery Validate驗證插件的使用代碼示例

時間:2024-09-19來源:風信官網(wǎng) 點擊: 767次
jQuery Validate 插件為表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單,同時提供了大量的定制選項,滿足應(yīng)用程序各種需求。該插件捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫用戶自定義方法的 API。所有的捆綁方法默認使用英語作為錯誤信息,且已翻譯成其他 37 種語言。

以下為JQuery Validate驗證插件在實際中項目運用中使用的代碼示例:

表單HTML代碼:
<form id="login-regis">
    <input type="hidden" name="inviterId" value="">
    <ul>
        <li>
            <input class="account" operaType="register" id="loginId" name="loginId" type="text" autocomplete="off" placeholder="請輸入常用手機號">
            <p class="error_mess"></p>
            <a href="/reset/password.html" class="last uhide">找回密碼</a>
        </li>
        <li>
            <input class="passw" id="password" name="password" type="password" autocomplete="off" placeholder="請輸入密碼">
            <p class="error_mess"></p>
            <span class="eye"></span>
            <div style="clear: both;"></div>
        </li>
        <li>
            <input class="short-message"  id="captcha" name="captcha" type="text" autocomplete="off" placeholder="請輸入短信驗證碼" value="">
            <a href="javascript:;" id="short_but">發(fā)送驗證碼</a>
            <p class="error_mess"></p>
            <div id="popup-captcha"> <div class="gt_input"> <input class="geetest_challenge" type="hidden" name="geetest_challenge"/> <input class="geetest_validate" type="hidden" name="geetest_validate"/> <input class="geetest_seccode" type="hidden" name="geetest_seccode" /> </div> </div>
        </li>
    </ul>
    <div class="text-center clearB"><a href="javascript:void(0);" class="agreen-regis" id="regisBtn">同意并注冊</a></div>
</form>

JQuery代碼:
$(function() {
    var loginCheck = {},
        flag = 1; //flag==0則驗證不通過
    var regTel = /^0?(13[0-9]|15[012356789]|17[0678]|18[0-9]|14[57])[0-9]{8}$/; //手機
    var regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/; //郵箱
    var operaType = $("#login-regis").attr("operaType");
    var shortCode = /[a-zA-Z0-9\!\(\)\-\~\@\.\_\^\#\%\&\*]{4,6}$/;
    // 登錄賬戶判斷
    loginCheck.account = function(obj) {
        var mes = "";
        if (($.trim(obj.val()) != "") && !regTel.test($.trim(obj.val()))) {
            flag = 0;
            obj.siblings(".error_mess").html("請輸入正確格式的手機號");
        } else {
            flag = 1;
            obj.siblings(".error_mess").html("");
        }
    }

    // 點擊眼睛圖片顯示密碼 mousedown顯示密碼 mouseup還原
    $(document).on("mousedown", ".loginSection .eye", function() {
        $("input[name='password']").attr("type", "text");
        $(document).on("mouseup", ".loginSection .eye", function() {
            $("input[name='password']").attr("type", "password");
        })
    })

    $("#login-regis input").keydown(function(event) {
        if (event.keyCode == 13) {
            if ($(this).is("#captcha")) {
                $("#login-regis").submit();
            } else {
                $(this).parent().next().find("input").focus();
            }
        }
    })
    // 登錄注冊提交前校驗
    $("#login-regis").validate({
        onkeyup : false,
        submitHandler : function(form) {
            if (flag != 0) { //驗證通過 可開始調(diào)登錄注冊接口
                if (operaType == "login") { // 2.新版登錄接口
                    $(form).find("#callbackurl").val(window.location.host);
                    form.submit();
                } else { // 開始調(diào)注冊接口
                    var thisHerf = window.location.href;
                    var params = {
                        loginId : $(".account").val(),
                        password : $(".passw").val(),
                        "captcha" : $("#captcha").val(),
                        "source" : thisHerf.indexOf("test-register.html") != -1 ? "test" : null
                    };

                    checkcount();
                    if (flag) {
                        requestAjax("post", "/registerV3", params, function(data) {
                            if (data.status == 200) { //注冊成功
                                location.assign('/register/more.html'); // 注冊成功后跳轉(zhuǎn)企業(yè)選擇頁面
                            } else { //注冊失敗
                                var img_src = passportUrl + '/captcha/image?t=' + Math.random();
                                $(".clickPic").removeAttr('src').attr("src", img_src);
                                $('.shibai').html(data.data.ERROR_MSG[0].messages[0]);
                                $("#login-regis li:eq(2) p").text(data.data.ERROR_MSG[0].messages[0]).show();
                            }
                        })
                    }

                }
            }
        },
        rules : {
            loginId : {
                required : true
            },
            password : {
                required : true,
                rangelength : [ 6, 20 ]
            },
            captcha : {
                required : true
            }
        },
        messages : {
            loginId : {
                required : "請輸入常用手機號"
            },
            password : {
                required : "請輸入密碼",
                rangelength : "密碼長度不正確"
            },
            /*checkPic: {
                required: "請輸入圖片驗證碼"
            }*/
            captcha : {
                required : "請輸入短信驗證碼"
            }
        },
        errorPlacement : function(error, element) {
            element.siblings(".error_mess").empty();
            error.appendTo(element.siblings(".error_mess"));
        }
    });



    // 點擊登錄/注冊按鈕開始調(diào)接口
    $("#loginBtn,#regisBtn").on("click", function() {
        $("#login-regis").submit();
    })

    //檢測(手機/郵箱)是否已經(jīng)注冊 未注冊則顯示立即注冊按鈕
    $(".account").blur(function() {
        checkcount();
    });

    function checkcount() {
        loginCheck.account($(".account"));
        if ($(".account").attr("operaType") != "login") { //登錄不需要驗證
            if (flag != 0 && ($.trim($(".account").val()) != "")) { //先判斷是否為正確格式 0 ==不是 1==是
                var params = {
                    loginId : $(".account").val(),
                    loginIdType : "register"
                };
                requestAjax("post", passportUrl + "/check/loginId", params, function(data) {
                    if (data.status != 200) { //已注冊
                        flag = 0; //賬號已注冊 不鞥呢通過驗證
                        $(".account").siblings(".error_mess").html("您填寫的賬號已存在");
                        $(".account").siblings(".last").removeClass("uhide");
                    } else {
                        flag = 1;
                        $(".account").siblings(".error_mess").html("");
                        $(".account").siblings(".last").addClass("uhide");
                    }
                })
            }
        }
    }

    function requestAjax(type, url, data, callback) {
        $.ajax({
            type : type,
            url : url,
            data : data,
            dataType : "json",
            success : function(data) {
                callback(data);
            }
        });
    }

    //極驗
    var handlerPopup = function(captchaObj) {
        // 成功的回調(diào)
        captchaObj.onSuccess(function() {
            var validate = captchaObj.getValidate();
            $.ajax({
                url : "/geet/validate.html", // 進行二次驗證
                type : "post",
                dataType : "json",
                data : {
                    username : $('#username1').val(),
                    password : $('#password1').val(),
                    geetest_challenge : validate.geetest_challenge,
                    geetest_validate : validate.geetest_validate,
                    geetest_seccode : validate.geetest_seccode
                },
                success : function(data) {
                    if (data && (data.status === "success")) {
                        var seconds = 60,
                            _this = $("#short_but"),
                            phone = null,
                            timer = null;

                        $.ajax({
                            url : "/captcha/phone/send",
                            type : "post",
                            data : {
                                "phone" : $("#loginId").val()
                            },
                            success : function(data) {
                                if (data.status == "200") {
                                    clearInterval(timer);
                                    timer = setInterval(function() {
                                        seconds--;
                                        _this.addClass("short-send");
                                        if (seconds > 0) {
                                            _this.html(seconds + "秒后重發(fā)");
                                        } else {
                                            clearInterval(timer);
                                            _this.html("重新發(fā)送").removeClass("short-send");
                                        }
                                    }, 1000);

                                    _this.siblings(".error_mess").html("");

                                } else if (data.status == "500") {

                                    _this.siblings(".error_mess").text(data.msg);

                                }
                            }
                        })

                    }
                }
            });
        });
        captchaObj.onError(function () {
            $.ajax({
                url: "/captcha/phone/1/cntEvent",
                type: "post",
                dataType: "json",
                success: function (json) {

                }
            });
        });
        captchaObj.onFail(function () {
            $.ajax({
                url: "/captcha/phone/1/cntEvent",
                type: "post",
                dataType: "json",
                success: function (json) {

                }
            });
        });
        $("#short_but").click(function() {

            $.ajax({
                url: "/captcha/phone/0/cntEvent",
                type: "post",
                dataType: "json",
                success: function (json) {

                }
            });

            var $loginId=$("#loginId");

            if($loginId.val()==""){
                $(".account").siblings(".error_mess").html("請輸入手機號");
                return;
            } else if (!/^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test($loginId.val())) {
                $(".account").siblings(".error_mess").html("請輸入正確格式的手機號");
                return;
            } else if ($loginId.val() == "" || $("#short_but").hasClass("short-send") || $(".loginSection form li:eq(0) p").text() == "您填寫的賬號已存在") {
                return;
            }
            captchaObj.show();
        });
        captchaObj.appendTo("#popup-captcha");
    };


    $.ajax({
        url : "/geet/register.html?t=" + (new Date()).getTime(),
        // 加隨機數(shù)防止緩存
        type : "get",
        dataType : "json",
        success : function(data) {
            initGeetest({
                gt : data.gt,
                challenge : data.challenge,
                product : "popup",
                offline : !data.success
            },
                handlerPopup);
        }
    });
})
熱門關(guān)鍵詞: JQuery Validate 驗證插件
欄目列表
推薦內(nèi)容
熱點內(nèi)容
展開