$("form").validate(
{
rules:{test1:{required:true},test2:{required:true}},
submitHandler:function(form){
//在Submit之前,且所有驗證成功。
//可以在這裡改成用$.ajax()送出。
$("#summary").html("");
return false;
},
invalidHandler:function(form){
//在Submit之前,且驗證失敗。
$("#summary").fadeOut().fadeIn();
},
success:function(error){
//單項證驗成功,參數是錯誤Element
//這callback也可以是文字,如果是文字會在error上加上class
error.addClass('valid').text('OK');
},
highlight:function(element, errorClass, validClass){
//單項證驗失敗,參數是驗證對向
$(element).addClass(errorClass).removeClass(validClass);
$(element).fadeOut().fadeIn();
},
unhighlight:function(element, errorClass, validClass){
//單項證驗成功,參數是驗證對向
$(element).removeClass(errorClass).addClass(validClass);
},
showErrors:function(){
//訊息顯示的Callback,名字取得不好,不是發生錯誤才會呼叫,而是只要有事件發生都會被呼叫,包含驗證成功。
$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below.");
//不呼叫defaultShowErrors其他如highlight,unhighlight等方法是不會被呼叫的
this.defaultShowErrors();
},
errorPlacement:function(error, element){
//錯誤element的加入function
//如果不想放在正後方可以加這個callback
error.appendTo(element.parent('td').next('td'));
}
});
<form>
<table>
<tr>
<th>Test1 : </th>
<td><input type='text' name='test1' /></td>
<td></td>
</tr>
<tr>
<th>Test2 : </th>
<td><input type='text' name='test2' /></td>
<td></td>
</tr>
<tr>
<th colspan='3'><input type='submit'></th>
</tr>
<tr>
<th colspan='3'><div id="summary"></div></th>
</tr>
</table>
<form>
td,th{
padding:5px
}
input.error{
border-color:#f33;
}
.error{
color:#f33;
}
input.valid{
border-color:#33f;
}
.valid{
color:#33f;
}
External resources loaded into this fiddle: