2013-04-24 132 views
0

使用jQuery-驗證1.11.0條件驗證使用jquery驗證

以我形式,我有一個條件是,如果文本是在字段A輸入端,字段乙&Ç成爲必需的。如果在字段B中輸入文字,則需要A & C等,等等。另外,如果字段D中有任何文本,請將其清除。

如果文本在字段D中輸入,則清除字段A,B,C並使其不是必需的。

我有一個錯誤,如果我首先填寫字段A,它似乎提交繞過其他2個字段的需要。如果我先填寫字段b或c,則確保字段A是必需的。

http://jsfiddle.net/rockitdev/mxtXX/47/

<form id="search" name="search" method="post" action=""> 
    <label for="a">Text A</label> 
    <input id="a" type="text" class="search-person" /> 
    <label for="b">Text B</label> 
    <input id="b" type="text" class="search-person" /> 
    <label for="c">Text C</label> 
    <input id="c" type="text" class="search-person" /> 
    <label for="d">Text D</label> 
    <input id="d" type="text" class="search-hcn" /> 
    <p> 
     <input class="btn btn-primary" type="submit" value="Submit" /> 
    </p> 
</form> 

$('.search-person').focus(function() { 
    $('.search-hcn').val(' ').removeClass("required"); 
    $('.search-person').addClass("required"); 
}); 

$('.search-hcn').focus(function() { 

    $('.search-person').val(' ').removeClass("required"); 
    $('.search-hcn').addClass("required"); 
}); 

$('#search').validate(); 
+0

所以使用需要驗證所有fields.Then它解決了不是所有的領域都需要一定的問題 – samba 2013-04-24 13:54:31

+0

。 .. – Rockitdev 2013-04-24 13:55:51

回答

3

設置在input領域name屬性解決了這個問題。

JSFiddle

<form id="search" name="search" method="post" action=""> 
    <label for="a">Text A</label> 
    <input id="a" type="text" class="search-person" name="person1" /> 
    <label for="b">Text B</label> 
    <input id="b" type="text" class="search-person" name="person2" /> 
    <label for="c">Text C</label> 
    <input id="c" type="text" class="search-person" name="person3" /> 
    <label for="d">Text D</label> 
    <input id="d" type="text" class="search-hcn" name="hcn" /> 
    <p> 
     <input class="btn btn-primary" type="submit" value="Submit" /> 
    </p> 
</form> 

debug選項是找到這樣的錯誤非常有用。

$('#search').validate({debug: true}); 
+2

值得一提的是,jQuery Validate插件要求'name'屬性總是出現在所有輸入元素上。 – Sparky 2013-04-24 19:58:58

6

您可以使用驗證插件爲此提供的depends選項。

注意:刪除值不是驗證的一部分

$('#search').validate({ 
    rules: { 
     a: { 
      required: { 
       depends: function(element) { 
        return $('#b').val().length > 0 || $('#c').val().length > 0 
       } 
      } 
     }, 
     b: { 
      required: { 
       depends: function(element) { 
        return $('#a').val().length > 0 || $('#c').val().length > 0 
       } 
      } 
     }, 
     c: { 
      required: { 
       depends: function(element) { 
        return $('#a').val().length > 0 || $('#b').val().length > 0 
       } 
      } 
     }, 
     d: { 
      required: { 
       depends: function(element) { 
        return $('#a').val().length == 0 || $('#b').val().length == 0 && $('#c').val().length == 0 
       } 
      } 
     } 
    } 
}); 

演示:Fiddle