对bootstrapValidator进行扩展、自定义校验

xiaoxiao2021-02-28  7

我们在用bootstrapValidator校验form表单的时候,它定义的notEmpty,regexp,stringLength等有时候并不能满足我们需要,这时可以自己进行扩展,自定义校验

1. 添加一个bootstrapValidator.min.extend.js

  

2.写自定义校验代码

// 对bootstrapValidator进行扩展 (function($) { //这里的notSameAndContinuity是验证的名字 //default是默认信息 $.fn.bootstrapValidator.i18n.notSameAndContinuity = $.extend($.fn.bootstrapValidator.i18n.notSameAndContinuity || {}, { 'default': 'Please enter a valid VIN number' }); //validate是验证的方法 $.fn.bootstrapValidator.validators.notSameAndContinuity = { validate: function(validator, $field, options) { var value = $field.val(); var reg = /(0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){5}\d/; var reg3 = /(9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){5}\d/; if (reg.test(value)) { return false; } if (reg3.test(value)) { return false; } var reg2 = /^(?=.*\d+)(?!.*?([\d])\1{5})[\d]{6}$/; if (!reg2.test(value)){ return false; } return true; } }; }(window.jQuery));

3.在js中运用自定义校验

// 第二步的表单 $('#form_step2').bootstrapValidator({ feedbackIcons : { valid : 'glyphicon glyphicon-ok', invalid : 'glyphicon glyphicon-remove', validating : 'glyphicon glyphicon-refresh' }, fields : { password : { validators : { notSameAndContinuity : { message : '密码必须为6位不相同、不连续的数字' } } }, repeatPassword : { validators : { notEmpty : { message : '密码不能为空' }, identical : { field : 'password', message : '密码不一致' } } } } });

4.updateStatus(field, status, validatorName)更新指定的字段状态。BootstrapValidator默认在校验某个字段合法后不再重新校验,当调用其他插件或者方法可能会改变字段值时,需要重新对该字段进行校验。

accountnoModal : { validators : { notEmpty : { message : '银行账号不能为空' }, regexp : { regexp : /^\d{12,22}$/, message : '银行账号为12~22位数字' }, callback : { callback : function(value, validator) { validator.updateStatus('accountnoConfirm', 'identical').validateField('accountnoConfirm'); return true; } } } }, accountnoConfirm : { validators : { notEmpty : { message : '确认银行账号不能为空' }, identical : { field : 'accountnoModal', message : '两次银行账号输入不一致' } } }
转载请注明原文地址: https://www.6miu.com/read-1250334.html

最新回复(0)