bootstrapValidator 封装
初始化
官方api:http://bootstrapvalidator.votintsev.ru/api/#is-valid-field
一些验证规则: https://blog.csdn.net/asd245025733/article/details/78061577?locationNum=7&fps=1
<form id="form">
<div class="form-group col-sm-6">
<label>输入框 :</label>
<input name="dyNo" type="text" class="form-control" placeholder="输入框" >
</div>
</form>
$('#form').bootstrapValidator({
fields: {
dyNo: {
validators: {
notEmpty: {
message:"不能为空"
},
digits: {
message: '请输入正整数。'
},
stringLength: {
min: 1,
max: 7,
message: '数据超长:7'
}
}
},
}
})
添加所有非空校验
/**
* 添加所有非空校验
* dom元素添加 notEmpty 属性
* @param formId
*/
function addAllNotemptyValidator(formId) {
$(formId + " [notEmpty]").each(function () {
var fieldName = this.name
var message = this.getAttribute("notEmpty") + "不能为空";
$(formId).bootstrapValidator("addField", fieldName, {
validators: {
notEmpty: {
message: message
},
}
});
})
}
添加字段长度校验
/**
* 添加字段长度校验 默认50
* dom元素添加 stringLength 设置长度
* @param formId
*/
function addAllStringLengthValidator(formId) {
$(formId + " input,textarea").each(function () {
if (this.type != "file" && this.type != "hidden") {
var fieldName = this.name
// console.log(formId,"fieldName ",fieldName,this)
var max = this.getAttribute("stringLength") || 50;
$(formId).bootstrapValidator("addField", fieldName, {
validators: {
stringLength: {
min: 0,
max: max,
message: '数据超长: ' + max
},
}
});
}
})
}
添加自定义校验
/**
* 添加自定义校验
* @param formId
* @param fieldName
* @param msg 不通过提示
* @param fun 判断逻辑
*/
function addCallbackValidator(formId, fieldName, msg, fun) {
$(formId).bootstrapValidator("addField", fieldName, {
trigger: "change",
validators: {
callback: {
message: msg,
callback: function (value) {
return fun(value)
}
},
}
});
}
是否启用字段校验
/**
* 是否启用字段校验
* @param formId
* @param fieldNames
* @param boolean
*/
function enableFieldValidator(formId, fieldNames, boolean) {
var bootstrapValidator = $(formId).data('bootstrapValidator');
for (var fieldName of fieldNames) {
bootstrapValidator.updateStatus(fieldName, "NOT_VALIDATED");
bootstrapValidator.enableFieldValidators(fieldName, boolean);
}
}
校验指定字段
/**
* 校验指定字段
* @param formId
* @param fieldNames
*/
function validatorFields(formId, fieldNames) {
var flag = true;
for (var fieldName of fieldNames) {
var bootstrapValidator = $(formId).data('bootstrapValidator');
bootstrapValidator.revalidateField(fieldName);
if (flag) {
flag = bootstrapValidator.isValidField(fieldName);
}
}
return flag;
}
校验表单
/**
* bootstrapValidator
* @param formid 表单id
* @returns {*|Boolean|boolean|jQuery}
*/
function validateForm(formid) {
var bootstrapValidator = $(formid).data('bootstrapValidator');
bootstrapValidator.validate();
return bootstrapValidator.isValid();
}