【问题标题】:jQuery validation not waiting for remote rulejQuery验证不等待远程规则
【发布时间】:2013-05-28 15:39:42
【问题描述】:

我正在尝试使用jQuery validation remote method 来检查值是否唯一 该规则是在提交时添加的,以防止在每次击键时触发它

var Id = $("#id").val();

$('#form').on('submit', function (e) {
    e.preventDefault();
    var newValue = $('#input').val();

$('#input').rules('add', {
    'remote': {
        url: '/MyController/CheckValue',
        type: 'POST',
        data: {
            id: Id,
            value: newValue
        }
    },
    messages: {
        'remote': 'This value is not valid'
    }
});

if ($('#form').valid()) {
    window.console.log('valid')
    // do something
}

$('#input').rules('remove', 'remote');
});

调用服务后操作返回真或假

[HttpPost]
public JsonResult CheckValue(int? id, string value)
{
    bool available;
    using (var myServiceClient = new MyServiceClient())
    {
        available = myServiceClient.IsValueAvailable(id, value);
    }
    return this.Json(available);
}

该规则工作正常,但$('#form').valid() 每次都返回true,因为它没有等待远程规则完成它的调用。

This post 建议在远程规则声明中使用async: false,但这会冻结浏览器。 documentation 中的示例没有使用这个,所以没有它应该可以工作。

我的验证规则有问题吗?

【问题讨论】:

    标签: jquery jquery-validate


    【解决方案1】:

    根据documentation,您应该将规则和验证方法直接附加到表单并使用submitHandler 回调,如下所示:

    $('#form').validate({
        rules: {
            inputName: {
              remote: {
                url: '/MyController/CheckValue',
                type: 'POST',
                data: {
                    id: Id,
                    value: newValue
                }
            }
        },
        messages: {
            inputName: {
                remote: 'This value is not valid'
            }
        },
        submitHandler: function(form){
            // Do Stuff with Form
        }
    }
    

    我希望这会有所帮助!

    【讨论】:

    • 关闭...该方法被称为.validate() 而不是.validation()
    • 感谢您的回答,但我忘了提到我正在使用 jQuery 验证和 MVC 非侵入式验证相结合,所以这个步骤已经由这个插件完成,并且非侵入式验证工作正常。我只想在表单上的现有验证中添加一个新规则,它适用于经典规则,但不适用于远程规则:表单在远程验证结果之前进行验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2020-04-18
    相关资源
    最近更新 更多