博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
bootstrapvalidator 校验
阅读量:7246 次
发布时间:2019-06-29

本文共 8595 字,大约阅读时间需要 28 分钟。

callback 函数可以写自己的方法校验

issueInvoiceForm.validation = function(){	$('#issueInvoiceForm').on('init.field.bv', function(e, data) {        var $icon      = data.element.data('bv.icon'),            options    = data.bv.getOptions(),                      // Entire options            validators = data.bv.getOptions(data.field).validators; // The field validators        if (validators.notEmpty && options.feedbackIcons && options.feedbackIcons.required) {        	$icon.addClass(options.feedbackIcons.required).show();        }    }).bootstrapValidator({        container:'popover',		feedbackIcons: {			required: 'glyphicon glyphicon-asterisk requiredStar',            valid: 'glyphicon glyphicon-ok',            invalid: 'glyphicon glyphicon-remove',            validating: 'glyphicon glyphicon-refresh'        },        fields: {        	invoiceDate:{validators: {notEmpty: {message: '开票日期不能为空'}}},//开票日期        	code:{validators: {notEmpty: {message: '发票编码不能为空'}}},        	amount:{        		validators:{        			notEmpty: {message: '发票金额不能为空'},        			 numeric: {message: '发票金额只能输入数字'},        			callback: {                         message: '开票金额小于选中金额',                         callback: function(value, validator) {                            return false;                         }                     }        		}        	},        	taxRate:{        		validators:{        			notEmpty: {message: '税率不能为空'},        			 numeric: {message: '税率只能输入数字'}        		}        	},        	taxAmount:{        		validators:{        			notEmpty: {message: '税额不能为空'},        			 numeric: {message: '税额只能输入数字'}        		}        	},        },group:'.validateDiv'	}).on('success.form.bv', issueInvoiceForm.issueInvoiceFormBtn).on('error.form.bv',function(){		 $("#issueInvoiceFormBtn").removeAttr("disabled");//将保存按钮去除disabled	     $(".has-error:visible:first").find(":input").focus();   });};
remote服务器校验

服务端验证代码(使用spring mvc)如下:

/*     * 返回String类型的结果     * 检查用户名的合法性,如果用户已经存在,返回false,否则返回true(返回json数据,格式为{"valid",true})     */    @RequestMapping(value = "/checkNameExistsMethod1", produces = "application/json;charset=UTF-8")    public @ResponseBody    String checkNameValidMethod1(@RequestParam String name) {        boolean result = true;        List
lstEmployees = employeeService.getAllEmployees(); for (Employee employee : lstEmployees) { if (employee.getName().equals(name)) { result = false; break; } } Map
map = new HashMap<>(); map.put("valid", result); ObjectMapper mapper = new ObjectMapper(); String resultString = ""; try { resultString = mapper.writeValueAsString(map); } catch (JsonProcessingException e) { e.printStackTrace(); } return resultString; }

这里需要说明的是bootstrap的remote验证器需要的返回结果一定是json格式的数据 :

{"valid":false} //表示不合法,验证不通过{"valid":true} //表示合法,验证通过

如果返回任何其他的值,页面验证将获取不到验证结果导致无法验证。

附一段完整的远程remote验证的代码加说明:

$(function(){/* 文档加载,执行一个函数*/     $('#defaultForm').bootstrapValidator({         message: 'This value is not valid',         feedbackIcons: {/*input状态样式图片*/             valid: 'glyphicon glyphicon-ok',             invalid: 'glyphicon glyphicon-remove',             validating: 'glyphicon glyphicon-refresh'         },         fields: {/*验证:规则*/             username: {//验证input项:验证规则                 message: 'The username is not valid',                                 validators: {                     notEmpty: {//非空验证:提示消息                         message: '用户名不能为空'                     },                     stringLength: {                         min: 6,                         max: 30,                         message: '用户名长度必须在6到30之间'                     },                     threshold :  6 , //有6字符以上才发送ajax请求,(input中输入一个字符,插件会向服务器发送一次,设置限制,6字符以上才开始)                     remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值,获得一个json数据。例表示正确:{"valid",true}                           url: 'exist2.do',//验证地址                         message: '用户已存在',//提示消息                         delay :  2000,//每输入一个字符,就发ajax请求,服务器压力还是太大,设置2秒发送一次ajax(默认输入一个字符,提交一次,服务器压力太大)                         type: 'POST'//请求方式                         /**自定义提交数据,默认值提交当前input value                          *  data: function(validator) {                               return {                                   password: $('[name="passwordNameAttributeInYourForm"]').val(),                                   whatever: $('[name="whateverNameAttributeInYourForm"]').val()                               };                            }                          */                     },                     regexp: {                         regexp: /^[a-zA-Z0-9_\.]+$/,                         message: '用户名由数字字母下划线和.组成'                     }                 }             },             password: {                 message:'密码无效',                 validators: {                     notEmpty: {                         message: '密码不能为空'                     },                     stringLength: {                         min: 6,                         max: 30,                         message: '用户名长度必须在6到30之间'                     },                     identical: {//相同                         field: 'password', //需要进行比较的input name值                         message: '两次密码不一致'                     },                     different: {//不能和用户名相同                         field: 'username',//需要进行比较的input name值                         message: '不能和用户名相同'                     },                     regexp: {                         regexp: /^[a-zA-Z0-9_\.]+$/,                         message: 'The username can only consist of alphabetical, number, dot and underscore'                     }                 }             },             repassword: {                 message: '密码无效',                 validators: {                     notEmpty: {                         message: '用户名不能为空'                     },                     stringLength: {                         min: 6,                         max: 30,                         message: '用户名长度必须在6到30之间'                     },                     identical: {//相同                         field: 'password',                         message: '两次密码不一致'                     },                     different: {//不能和用户名相同                         field: 'username',                         message: '不能和用户名相同'                     },                     regexp: {//匹配规则                         regexp: /^[a-zA-Z0-9_\.]+$/,                         message: 'The username can only consist of alphabetical, number, dot and underscore'                     }                 }             },             email: {                 validators: {                     notEmpty: {                         message: '邮件不能为空'                     },                     emailAddress: {                         message: '请输入正确的邮件地址如:123@qq.com'                     }                 }             },             phone: {                 message: 'The phone is not valid',                 validators: {                     notEmpty: {                         message: '手机号码不能为空'                     },                     stringLength: {                         min: 11,                         max: 11,                         message: '请输入11位手机号码'                     },                     regexp: {                         regexp: /^1[3|5|8]{1}[0-9]{9}$/,                         message: '请输入正确的手机号码'                     }                 }             },             invite: {                 message: '邀请码',                 validators: {                     notEmpty: {                         message: '邀请码不能为空'                     },                     stringLength: {                         min: 8,                         max: 8,                         message: '请输入正确长度的邀请码'                     },                     regexp: {                         regexp: /^[\w]{8}$/,                         message: '请输入正确的邀请码(包含数字字母)'                     }                 }             },         }     })     .on('success.form.bv', function(e) {//点击提交之后         // Prevent form submission         e.preventDefault();         // Get the form instance         var $form = $(e.target);         // Get the BootstrapValidator instance         var bv = $form.data('bootstrapValidator');         // Use Ajax to submit form data 提交至form标签中的action,result自定义         $.post($form.attr('action'), $form.serialize(), function(result) {//do something...});     });});

转载地址:http://ifbbm.baihongyu.com/

你可能感兴趣的文章
阿里巴巴Java开发规范---个人总结
查看>>
varchar(MAX)--SQL2005的增强特性
查看>>
HDOJ2026 ( 首字母变大写 )
查看>>
每个网页设计者都自以为是
查看>>
漂亮的Windows Mobile设备中心
查看>>
爆牙齿的新发现:先clear:left才能正常position:absolute。
查看>>
DOTween文档
查看>>
HDOJ1253 胜利大逃亡 【三维BFS】
查看>>
JQuery: 基本知识了解
查看>>
iOS开发-简单工厂模式
查看>>
F#探险之旅(二):函数式编程(下)
查看>>
使用Eclipse Memory Analyzer 进行JAVA内存泄露分析
查看>>
快速排序性能分析
查看>>
常见c++笔试题整理(含答案)page26
查看>>
iOS:点击button卡死
查看>>
QTP的那些事--有关datatable对象的使用
查看>>
WebForm-带接口工厂模式的三层架构
查看>>
MEF TIP1:基础
查看>>
jquery网页倒计时效果,秒杀,限时抢购!
查看>>
windows常用命令
查看>>