自定義預設值
Overriding jQuery validation highlight / unhighlight methods
Ex. 讓jQuery validate和 act-bootstrap錯誤顯示能相容
1 2 3 4 5 6 7 8 9 10 11 | jQuery.validator.setDefaults({ errorElement: 'div' , errorClass: 'help-block' , highlight: function (e) { $(e).closest( '.form-group' ).removeClass( 'has-info' ).addClass( 'has-error' ); }, success: function (e) { $(e).closest( '.form-group' ).removeClass( 'has-error' ); $(e).remove(); } }); |
依據別欄位的值而決定是否必填
jquery validate plugin require field if another field has a value and vice versa
http://stackoverflow.com/questions/10406089/jquery-validate-plugin-require-field-if-another-field-has-a-value-and-vice-versa
Ex. 在 $("form select[name='status']") 值為4時,remark必填
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $( 'form' ).validate({ rules: { remark: { required: { depends: function (element) { return $( "form select[name='status']" ).val() === "4" } } } }, messages: { remark: { required: "備註必填" // 只有在 $("form select[name='status']") 值為4時才必填 } } }); |
客製化驗證方法
http://stackoverflow.com/questions/17561615/creating-a-custom-rule-in-jquery-validate
Ex. 輸入日期不能為未來日期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | jQuery.validator.addMethod( "endDateToday" , function (value, element) { //Your Validation Here var open_time = new Date(value); var today = new Date(); if (open_time > today) { return false ; // return bool here if valid or not. } else { return true ; // return bool here if valid or not. } }, "不能輸入未來日期" ); // 預設的錯誤訊息 $( 'form' ).validate({ rules: { open_time: { endDateToday: true } } }); |
沒有留言:
張貼留言