jQuery远程验证:将远程数据传递给函数 [英] jquery remote validation: pass remote data to function

查看:65
本文介绍了jQuery远程验证:将远程数据传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码

var validator = $("#form-utente").validate( {
    rules: {
        login: { checkLogin: true }
    }
}

我的"checkLogin"功能...

my "checkLogin" function ...

$.validator.addMethod("checkLogin", function(value, element) {
    return eval($.ajax({
        url: "checkLogin.cfm",
        async: false,
        data: {
            login: function() {
                return $("#login").val();
            },
        }
    }).remoteData);
});

checkLogin.cfm(remoteData)在需要"true"时返回"false",反之亦然.

checkLogin.cfm (remoteData) returns "false", when I need "true", and viceversa.

我如何评估远程数据? ...

how i can evaluate remote data? ...

我需要类似的东西:

rules: {
    login: { checkLogin: function(remoteData) {
        if(remoteData == true) {
            return false;
        } else {
            return true;
        }
    }}
}

有什么主意吗?

推荐答案

通常,您将使用jquery.validate中的remote规则进行使用远程服务的验证.您的实现假设有一个同步调用,根据jQuery文档,该调用可能会临时锁定浏览器,并在请求处于活动状态时禁用任何操作".如果在每次更改或模糊事件(例如默认验证行为)之后都对其进行检查,则可能会变得非常糟糕.

Typically you'd use the remote rule in jquery.validate for validation that uses a remote service. Your implementation supposes a synchronous call, which according to the jQuery docs might "temporarily lock the browser, disabling any actions while the request is active". This might get pretty bad if it's being checked after every change or blur event, like the default validation behavior.

不幸的是,remote没有为您提供一个钩子来更改您解释接收到的数据的方式:

Unfortunately, remote doesn't provide a hook for you to change how the data you receive is interpreted:

success: function(response) {
    ...
    var valid = response === true;

虽然您可以在设置规则时覆盖success的实现,但这将要求您复制规则用于管理表单验证状态的逻辑(

While you can override the implementation of success when you setup your rules, this would require you to duplicate the logic used by the rule to manage the validation state of the form (lines 1035 - 1050).

所以...假设您对插件做了一些小的改动,如下:

So... let's say you make a small alteration to the plugin along the lines of:

success: function(response) {
    ...
    var valid = ($.isPlainObject(param) && param.isValidResponse) ?
        param.isValidResponse(response) : 
        response === true;

然后将您的规则设置为:

And then setup your rule as:

login: {
    remote: {
        url: "checkLogin.cfm",
        data: {
            login: function() {
               return $("#login").val();
            },
        },
        isValidResponse: function(response) {
            // do something with response
            // return true or false
        }
    }
}

然后,您应该能够以任何需要的方式解析响应.让我知道是否有帮助.

You should then be able to parse the response any way that's needed. Let me know if this helps.

这篇关于jQuery远程验证:将远程数据传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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