2012-08-25 44 views

回答

1

你在找什麼叫在jQuery驗證一個dependency-expression。如果你的表格看起來你顯示什麼(即2個輸入,一個名爲image另一個叫images),你可以這樣做:

$('form').validate({ 
    rules: { 
     image: { 
      required: 'input[name="images"]:blank' 
     }, 
     images: { 
      required: 'input[name="image"]:blank' 
     } 
    } 
}); 

那麼,什麼情況是,當它來驗證每個表單域,它會檢查給定的表達式,如果它返回true,那麼當前的表單字段是必需的。如果它是假的,那麼它不是。

0

這可能工作還沒有測試它只是寫它作爲quicky以幫助ü在路上

$(function() { 
    $("input").focusout(function(){ 
     $('input').each(function(){ 
      $(this).addClass('required'); 
      if($(this).val()){ 
       $(this).removeClass('required'); 
      } 
     }); 
    }); 
}); 

Here is a fiddle:

0

我通常添加自定義的方法,這樣的東西。嘗試這樣的事情。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script> 
    <style> 
     .error {color: red} 
    </style> 

    <form id="testForm" enctype="multipart/form-data"> 

     <input name="image" class="oneof" /> 
     <br /><input name="images" type="file" class="oneof" /> 
     <br /><input type="submit" /> 
    </form> 


    <script> 
     // using custom methods 
     $(document).ready(function(){ 
      jQuery.validator.addMethod("oneofelementsrequired", function(value, element, param) { 
       element = element || false; 
       var $frm=$(element).parents('form:first'), 
        any=false, 
        $ctrls=$frm.find(param); 

       $ctrls.each(function(){ 
        any = any || this.value != '' 
       }); 
       return any; 
      }, "Please fill one of this fields"); 

      jQuery.validator.addClassRules({ 
       oneof: {oneofelementsrequired: '.oneof'} 
      }); 

      $('#testForm').validate({ 
       submitHandler: function(){ 
        alert('From is Ok'); 
        return false; 
       } 
      }); 


     }); 

    </script> 

demo