2013-02-09 71 views
5

我正在使用jQuery驗證來驗證窗體,並且我想要做的是這個...我想設置它,所以如果複選框被選中而不是編輯框例如,驗證方式不同。當檢查複選框時動態更改jQuery驗證規則

這是怎麼回事,如果未選中該複選框,應驗證:

weight: { required: true, max: 50 } 

這是怎麼若檢驗應該進行驗證。

weight: { required: true, max: 100 } 

任何想法?

回答

7

無論何時單擊複選框,您都會使用Validate plugin's built-in rules('add') method來動態更改規則。

jQuery的

$(document).ready(function() { 

    // initialize the plugin 
    $('#myform').validate({ 
     // other options, 
     rules: { 
      // other rules, 
      weight: { 
       required: true, 
       max: 50 // initial value on load 
      } 
     } 
    }); 

    // change the rule on checkbox and update displayed message dynamically 
    $('#check').on('change', function() { 
     if ($(this).is(':checked')) { 
      $('#weight').rules('add', { 
       max: 100 
      }); 
     } else { 
      $('#weight').rules('add', { 
       max: 50 
      }); 
     }; 
     $('#weight.error').each(function() { 
      $(this).valid(); 
     }); 
    }); 

}); 

HTML

<form id="myform"> 
    <input type="checkbox" id="check" /> 
    <input type="text" id="weight" name="weight" /> 
    <input type="submit" /> 
</form> 

工作演示:http://jsfiddle.net/3hGxS/

3

使用的max方法和作爲PA的功能做一個規則rameter。當字段被驗證時,即當在字段上調用element()時,這將被評估。

規則的定義是這樣的

rules: { 
    field1: 
    { 
     required: true, 
     max: function() { return $("#mycheckbox:checked").length ? 100 : 50; } 
    } 
} 

此外,重新驗證目標字段時,規則的改變,或者你可能會留下不再適用

$('#mycheckbox').on('change', function() { 
    $('#field1.error').each(function() { 
     $(this).valid(); 
    }); 
}); 

注意,這僅重新驗證錯誤消息該字段是否已被驗證,檢查是否存在默認的errorClass'錯誤'。

與像HTML這樣

<input name="mycheckbox" id="mycheckbox" type="checkbox" /> 
<input name="field1" id="field1"> 
<input type="submit" /> 

完整的JavaScript代碼是這樣的,find the fiddle here

$(function() { 

    $("form").validate({ 
     rules: { 
      field1: 
      { 
      required: true, 
      max: function() { 
        return $("#mycheckbox:checked").length ? 100 : 50; 
       } 
      } 
     }, 
     submitHandler: function() { 
      alert('form ok'); 
     } 
    }); 

    $('#mycheckbox').on('change', function() { 
     $('#field1.error').each(function() { 
      $(this).valid(); 
     }); 
    }); 

});