2010-10-08 125 views
14

如何使用三個規則驗證電子郵件地址字段,並在div容器中包含三條自定義消息。 即。jquery使用多個規則驗證

rules: { 
    email: { 
     validationRule: true, 
     email: true, 
     remote: '/ajax/emailDuplicationCheck.php' 
     } 
    } 

如果第一個假消息應該是「驗證規則失敗」

如果第二個假(失敗)「輸入電子郵件地址」

如果第三(遠程)失敗。消息應該是「帳戶已存在於數據庫中」。

我可以爲所有規則添加一條消息,但是我想根據規則自定義消息。

回答

11

試試這個:

$("#myForm").validate({ // Replace #myForm with the ID of your form 
    rules: { 
     email: { 
      required: true, 
      email: true, 
      remote: { 
       url: "/ajax/emailDuplicationCheck.php", 
       type: "post", 
       data: { email: function() { 
        return $("#email").val(); // Add #email ID to your email field 
       } 
      } 
     } 
    }, 
    messages: { 
     email: { 
      required: 'Email address is required', 
      email: 'Please enter a valid email address', 
      remote: 'This email address has already been used' 
     } 
    }, 
    errorPlacement: function(error) { 
     $("#response").html(error); 
    } 
}); 

希望這有助於!

+0

它不工作號。它只在電子郵件中顯示該消息:「輸入電子郵件地址」。如我所說。我想在div容器中顯示味精? – Developer 2010-10-08 12:40:58

+0

語法是正確的,這就是它應該完成的方式,所以問題必須在其他地方。 'validationRule'看起來像一個自定義驗證方法。究竟應該做什麼?你可以編輯你的問題,並添加該方法的代碼? – 2010-10-08 12:46:22

+0

validationRule方法無所作爲。它只是返回true。好,如果我刪除該行。甚至比不符合兩條規則。以及如何將它顯示在id #response的Divcontainer中。我想在div容器中顯示消息 – Developer 2010-10-08 13:08:41

1

對於每個規則,您可以使用自定義驗證規則以及您自己的自定義消息。

爲了簡單起見,下面是如何驗證「用戶名」輸入具有用於驗證三個自定義的方法(每個具有其自己的錯誤信息)的一個例子:

// Add three custom methods first: 

$.validator.addMethod("nameCustom", function(value, element) { 
    return this.optional(element) || /^[a-zA-Z ]+/.test(value); 
}, 'Please use english letters only.'); 

$.validator.addMethod("noSpaceStart", function(value, element) { 
    return value.indexOf(" ") != 0; 
}, "Name cannot start with a space"); 

$.validator.addMethod("noSpaceEnd", function(value, element) { 
    return value.lastIndexOf(" ") != value.length - 1; 
}, "Name cannot end with a space"); 

$('#form_to_validate').validate({ 
    rules: { 
     username: { 
      // Add the custom validation methods to the username input 
      noSpaceStart: true, 
      noSpaceEnd: true, 
      nameCustom: true, 
      // required and maxlength are built-in methods in the plugin and are ready to be used 
      required: true, 
      maxlength: 50 
     } 
    } 
});