2014-05-09 27 views
-1

我有两个文本框,我正在应用jQuery验证规则。我已经这样做了,它工作正常,但我想从两个框中选择提交像我想要至少在框中归档。如果我留空他们都应该给予错误所以如何运用这一点,我在下面如何使用jQuery验证应用可选验证

<script> 
$.validator.addMethod("box_not_same", function(value, element) { 

    return $('#box2').val() == value; 
}, "box1 value and box2 value cannot be same.."); 

    $("#f1").validate({ 
     rules: { 
      box1: "required", 

      box2: { 
        required: true, 
        Password_not_same:true  
       } 
     }, 
     messages: { 
      box1: "Enter box1 value", 
      box2: { 
        required : "Enter value in box2", 
        box_not_same:"box1 value and box2 value cannot be same.",  
       } 

     } 

    }); 
</script> 
<input id="box1" name="box1" value=""/> 
<input id="box2" name="box2" value=""/> 
+0

什么是'Password_not_same'? – Bergi

+0

请修正您的拼写和语法,以便我们可以更好地了解您想要的内容。 – Sparky

回答

0

报价OP给这个代码需要什么样的变化:

“我有两个文本我和 已经做到了这一点,它工作正常,但我想从我想要至少在框中提交的两个框中选择提交像 。如果我离开 空白他们两个它应该给出错误“

如果我理解正确,你有两个文本输入和用户必须填写一个或另一个?

在这种情况下,您可以使用中包含的the require_from_group method

rules: { 
    box1: { 
     require_from_group: [1, "[name^='box']"] 
    }, 
    box2: { 
     require_from_group: [1, "[name^='box']"]  
    } 
}, 

在你的情况下,我使用的“开始以”选择的目标,其name开始与box所有元素。

DEMO:http://jsfiddle.net/3T8Tr/

这是文档:http://jqueryvalidation.org/category/methods/#require-from-group-method