2012-09-19 159 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" />