JQuery.validate-仅适用于模糊的一条规则;其余应该正常吗? [英] JQuery.validate - one rule on blur only; the rest should be normal?

查看:72
本文介绍了JQuery.validate-仅适用于模糊的一条规则;其余应该正常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小提琴,以显示我要对用户ID字段进行的简单验证:

  1. 将其设为必填项(请尽可能积极地进行验证)
  2. 设置最小长度(尽可能积极地进行验证)
  3. 设置最大长度(尽可能积极地进行验证)
  4. 运行AJAX调用以确保用户ID不存在(我只想在模糊状态下运行它)

我不使用validate()-远程规则,因为我想返回一个自定义对象,而不仅仅是一个简单的字符串.如果远程可以做到这一点,那么它仅在模糊时调用规则,那么我可以尝试一下. (我所有的AJAX响应都遵循一个设置的对象定义.)

HTML

<form action="#" method="get" id="register-wizard">User ID:
    <br />
    <input type="text" class="form-control required confirm-me" id="User_UserId" name="User.UserId" autocomplete="off" />
    <div class="loader user-id hide" style="display: none;"><i class="icon-spinner icon-spin icon-large"></i> (Checking...)</div>
    <p>
        <button id="next">Next</button>
    </p>
</form>

JavaScript

var $wizardForm = $("#register-wizard");
var $validator = $wizardForm.validate({
    rules: {
        "User.UserId": {
            required: true,
            minlength: 3,
            maxlength: 125,
            userIdCheck: true
        }
    }
});

$("#next").click(function (e) {
    e.preventDefault();    
    //do validations before moving onto the next tab in the wizard
    var $valid = $wizardForm.valid();
    if (!$valid) {
        $validator.focusInvalid();
        return false;
    }
});    
jQuery.validator.addMethod("userIdCheck", function (value, element) {
    var validator = this;
    this.startRequest(element);    
    var $loader = $(".loader.user-id");    
    $.ajax({
        url: "/echo/json/",
        type: "POST",
        data:{
            json: JSON.stringify({
                text: 'some text'
            }),
            delay: 1
        },
        success: function (result) {
            console.log("result: ")
            console.log(result);

            validator.stopRequest(element, true);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("A server error occurred.\n\n" + textStatus);
        },
        beforeSend: function () {
            $loader.show();
        },
        complete: function () {
            $loader.hide();
        }
    });

return "pending";
}, "The user ID is already in use");

这是我的小提琴: http://jsfiddle.net/eHu35/3/

解决方案

引用标题:仅一条规则适用于模糊;其余规则应正常吗?"

否,各种触发事件,例如onfocusoutonkeyup等,都是在每个字段"的基础上触发的.您不能在一个字段上使用一个规则(例如min)在所有事件上正常触发,而在同一字段上使用另一个规则(例如remote)仅由onfocusout触发. (但是,您可以在不同的字段中使用不同的事件.)

在我所见过的关于该主题的大多数SO线程中,用户都将禁用onkeyup以防止remote规则的持续过早触发.例如,在测试重新验证码时,需要禁用onkeyup,因为每次失败都会生成新代码.

I've worked on a fiddle to show the simple validation that I'm trying to do for my user ID field:

  1. Make it required (validate as aggressively as possible)
  2. Set a minimum length (validate as aggressively as possible)
  3. Set a maximum length (validate as aggressively as possible)
  4. Run an AJAX call to ensure user ID doesn't already exist (I want to only run this on blur)

I'm not using the validate() - remote rule because I wanted to have a custom object returned instead of just a simple string. If that's possible with remote and it only calls the rule on blur, then I can try for that. (All of my AJAX responses adhere to a set object definition.)

HTML

<form action="#" method="get" id="register-wizard">User ID:
    <br />
    <input type="text" class="form-control required confirm-me" id="User_UserId" name="User.UserId" autocomplete="off" />
    <div class="loader user-id hide" style="display: none;"><i class="icon-spinner icon-spin icon-large"></i> (Checking...)</div>
    <p>
        <button id="next">Next</button>
    </p>
</form>

JavaScript

var $wizardForm = $("#register-wizard");
var $validator = $wizardForm.validate({
    rules: {
        "User.UserId": {
            required: true,
            minlength: 3,
            maxlength: 125,
            userIdCheck: true
        }
    }
});

$("#next").click(function (e) {
    e.preventDefault();    
    //do validations before moving onto the next tab in the wizard
    var $valid = $wizardForm.valid();
    if (!$valid) {
        $validator.focusInvalid();
        return false;
    }
});    
jQuery.validator.addMethod("userIdCheck", function (value, element) {
    var validator = this;
    this.startRequest(element);    
    var $loader = $(".loader.user-id");    
    $.ajax({
        url: "/echo/json/",
        type: "POST",
        data:{
            json: JSON.stringify({
                text: 'some text'
            }),
            delay: 1
        },
        success: function (result) {
            console.log("result: ")
            console.log(result);

            validator.stopRequest(element, true);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("A server error occurred.\n\n" + textStatus);
        },
        beforeSend: function () {
            $loader.show();
        },
        complete: function () {
            $loader.hide();
        }
    });

return "pending";
}, "The user ID is already in use");

Here's my fiddle: http://jsfiddle.net/eHu35/3/

解决方案

Quote Title: "one rule on blur only; the rest should be normal?"

No, the various triggering events, like onfocusout, onkeyup, etc., are triggered on a "per field" basis. You cannot have one rule on a field, say min, triggered normally on all events, while another rule for the same field, say remote, is triggered only by onfocusout. (You can, however, have different events for different fields).

In most of the SO threads on this topic I've seen, the user will disable onkeyup in order to prevent the constant premature triggering of the remote rule. When testing a re-captcha code, for example, disabling onkeyup is required as a new code is generated every time one fails.

这篇关于JQuery.validate-仅适用于模糊的一条规则;其余应该正常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆