0

我在远程检查电子邮件地址时遇到 jquery 验证插件问题。

远程函数返回一个 JSON 字符串,如:

"{ "isValid": "true", "email": "email@email.com"  }"

我知道 jquery 验证中的默认设置应该只包含一个返回 true 或 false 的 json 字符串。但我需要返回检查的电子邮件。

是否可以使用远程验证功能来检查 json 属性“isValid”?

谢谢,

詹姆斯福特

4

3 回答 3

3

要处理来自自定义远程验证调用的响应,您必须创建自定义规则。在此示例中,我们正在检查用户 nick 是否可用。

jquery 验证自定义规则:

$('#nick').rules("add", {
  // nick is required
  required: true,
  // nick can have from 3 to 30 characters
  rangelength: [3,30],
  remote: {
    url: "/your-api-url",
    type: "GET",
    data: {
      // nick is id of input field from html
      nick: function() {
          // get user input from field value
          return $('#nick').val();
      }
    },
    // custom filtering response from api call
    dataFilter: function(data) {
      // we need to parse data string to json
      var json = JSON.parse(data);
      if(json.nick === "true" || json.nick === true) {
          // jquery validate remote method
          // accepts only "true" value
          // to successfully validate field 
          return '"true"';
      } else {
          // error message, everything that isn't "true"
          // is understood as failure message
          return '"This nick is already taken."';
      }
    }
  }
});

如果 nick 可用,则来自 api 的响应:

{nick:true}

html:

<input name="nick" id="nick" value="" placeholder="Nick" type="text" />
于 2015-02-22T21:36:27.720 回答
2

您可以轻松扩展验证器插件。您所要做的就是使用$.validator.addMethod(),添加一个进行远程调用的方法,获取您显示的 JSON 字符串,执行您需要返回电子邮件地址的任务,并在最后将 true 或 false 返回到验证流程。

这可能会有所帮助:http ://docs.jquery.com/Plugins/Validation/Validator/addMethod#namemethodmessage

于 2012-09-20T09:01:18.230 回答
2

我认为您可以使用 remote() 作为源编写自定义方法。就像是

jQuery.validator.addMethod("customRemote", function(value, element, param) {

...
// the piece of code doing AJAX response parsing

success: function(response) {
    validator.settings.messages[element.name].remote = previous.originalMessage;

    // original:
    var valid = response === true || response === "true";

    // replace with your own logic
    if(response.isValid == "true" && something == else) {
        // do the stuff
    }

...

})
于 2012-09-20T09:16:17.657 回答