参考 http://blog.csdn.net/windxxf/article/details/7520340
//1.依赖
<script src="/javascripts/jquery-2.0.3.min.js"></script>
<script src="/javascripts/jquery.validate.min.js"></script>
//2.自定义校验规则
$.validator.addMethod("isChinese", function (value, element) {
var chinese = /^[\u4e00-\u9fa5]+$/;
return this.optional(element) || (chinese.test(value));
},
"请输入汉字");
//3.设置只校验不提交
$.validator.setDefaults({
debug: true
});
//4.校验
$('#newsForm').validate({
errorElement: 'span', //错误提示显示在创建的span元素中
errorClass: 'has-error', //错误提示的样式,这里是用的bootstrap
focusInvalid: false,
rules: {
module: { //module对应的是表单元素名称,不是id
required: true
},
forward2: {
required: true
},
forward1: {
required: true
},
title: {
required: true
},
image1: {
required: true
},
image2: {
required: true
}
},
messages: {
module: {
required: '请选择文章分类'
},
forward2: {
required: '请输入导语2'
},
forward1: {
required: '请输入导语1'
},
title: {
required: '请输入标题'
},
image1: {
required: '请选择列表图片'
},
image2: {
required: '请选择详情图片'
}
},
highlight: function (e) { //校验失败高亮显示当前元素(e)的父级元素(带form-group类的父级)
$(e).closest('.form-group').addClass('has-error');
},
success: function (e) { //校验成功取消刚才高亮显示
$(e).closest('.form-group').removeClass('has-error');
$(e).remove(); //删除错误提示元素
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent()); //错误元素显示的位置
}
});
//5.提交时校验,失败代码停止运行
$('#sub').click(function () {
/** start of 校验*/
if (!$('#newsForm').valid()) {
return;
}
/** end of 校验*/
... ...
});
网友评论