2012-09-19 121 views
0

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

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

"{ "isValid": "true", "email": "[email protected]" }" 

我知道在jQuery验证默认设置只能由一个JSON字符串返回真或假的。但我需要返回检查的电子邮件。

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

感谢,

詹姆斯·福特

回答

2

我想你可以使用遥控器编写自定义方法()作为源。类似于

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 
    } 

... 

}) 
2

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

jQuery验证对自定义规则:从API

$('#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:true} 

HTML:

<input name="nick" id="nick" value="" placeholder="Nick" type="text" />