2009-06-23 72 views
4

我添加了一個自定義驗證方法來驗證密碼。然而,這並不重要,如果我得到的JSON是:使用自定義方法擴展JQuery Validator插件

{"success":true} 

或:

{"success":false} 

領域密碼從未驗證。

$(document).ready(function() { 
    // Ad custom validation 
    $.validator.addMethod('authenticate', function (value) { 
    $.getJSON("./json/authenticate.do",{ password: value},function(json) { 
       return (json.success == true) ? true : false;} 
      ); 
    }, 'Wrong password'); 

    $('form#changePasswordForm').validate({ 
      rules: { 
       repeat_new_password: { equalTo: "#new_password" }, 
       password : {authenticate: true} 
     }, submitHandler: function(form) { 
        $(form).ajaxSubmit({ 
          dataType: "json", 
          success: function(json) { 
          alert("foo"); 
        } 
     });      
    } 
});   
}); 

任何想法,我做錯了什麼?

回答

7

你做錯了什麼是當你添加自定義方法時,你永遠不會從它返回true或false。你在ajax回調中返回它。

$.validator.addMethod('authenticate', function (value) { 
    $.getJSON("./json/authenticate.do",{ password: value }, function(json) { 
     // This return here is useless 
     return (json.success == true) ? true : false; 
    }); 
    // You need to return true or false here... 
    // You could use a synchronous server call instead of asynchronous 
}, 'Wrong password'); 

不是添加自定義的方法,你可以使用remote功能:

$('form#changePasswordForm').validate({ 
    rules: { 
     repeat_new_password: { 
      equalTo: "#new_password" 
     }, 
     password : { 
      // This will invoke ./json/authenticate.do?password=THEVALUE_OF_THE_FIELD 
      // and all you need to do is return "true" or "false" from this server script 
      remote: './json/authenticate.do' 
     } 
    }, 
    messages: { 
     password: { 
      remote: jQuery.format("Wrong password") 
     } 
    }, 
    submitHandler: function(form) { 
     $(form).ajaxSubmit({ 
      dataType: "json", 
      success: function(json) { 
       alert("foo"); 
      } 
     });      
    } 
}); 

您可以檢查出來的行動here

+0

你比我還多7.000點,徽章少。徽章系統顯然有些問題。 – 2009-06-24 11:18:01