2013-08-27 62 views
0

我想使用jQuery驗證來驗證我們的數據庫的電子郵件輸入字段,以查看電子郵件ID是否已存在。使用jQuery驗證處理空響應

輸入字段看起來像這樣。

<input name='email' id='id_email'/> 

驗證是這樣完成的。我稍後將綁定remote規則。

var validator = $('form').validate({ 
     rules: { "email": {required:true,email:true} }, 
     messages: { "email": { 
      required:'Please enter your email ID.', 
      email:'Please enter a valid email ID.', 
      remote: $.format('{0}') 
     }} 
}); 

$('#id_email').rules('add', { 
     remote:{ 
      url:'/validate/', 
      type:'post', 
      dataType:'text', 
      data:{'id_email':function() { return $('#id_email').val(); }} 
     } 
}); 

現在,服務器會如果驗證通過,並顯示錯誤消息(一些純文本)如果驗證失敗,或沒有迴應。

驗證失敗時,我可以正確顯示來自服務器的錯誤消息。但是,當輸入有效的電子郵件ID並且服務器以空響應迴應時,錯誤消息會顯示輸入字段的值。我如何將此視爲true驗證並且不顯示任何錯誤消息?

+1

你爲什麼不只是從服務器返回 '真'?這就是插件所期望的,所以你不需要做任何特殊的事情 –

+0

這可能會破壞一些其他的東西,因爲有些情況下用於驗證(其他字段)我們返回單個字段的不同響應的情況。 – GPX

回答

0

不幸的是,這是the remote method與這個插件一起使用的方式。如果您從服務器返回true,則元素有效...如果服務器返回false,null或未定義,則該元素顯示消息並且該元素被視爲無效。

「......必須是有效的元素,真實的,可以是任何虛假,未定義或爲空的無效元素」

也許你可以編寫自己的自定義remote方法...只要確保方法返回true爲您的特定響應。

jQuery.validator.addMethod("customRemote", function(value, element, params) { 
    // your ajax; 
    // if server response is something good, then return true 
    // if server response is not so good, then return false and error message displays 
}, "This is the error message"); 

參見:http://jqueryvalidation.org/jQuery.validator.addMethod/

+0

看起來我沒有其他選擇,如果我有服務器發送自定義響應。 – GPX