背景
项目中使用bootstrap做前端,需要用bootstrapValidator.js做验证插件。网上找了一遍,没有支持bootstrap4.0版本的验证插件,自己动手把bootstrapValidator.js的样式整理下。
版本号
Bootstrap v4.0.0-beta (https://getbootstrap.com)
jQuery v3.2.1
bootstrapValidator.js
源码下载地址
http://download.youkuaiyun.com/download/l2000h_ing/10116143
解决办法
1.bootstrap4.0没有bootstrapValidator样式,需要找bootstrap3.0-4.0之间的样式。先copy出来。
1.customValidator.css
2.添加fonts
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
glyphicons-halflings-regular.ttf
glyphicons-halflings-regular.woff
3.代码展示
<form>
<div class="row">
<div class="col-md-6 form-label">
<label class="form-control-static">名称</label>
<div class="form-group">
<input id="inputName" name="inputName" placeholder="例如:myServiceName" type="text"
value="${(service.name)!""}" maxlength="50"
<#if (opt) == "edit">readonly="readonly"</#if>
class="ember-view ember-text-field form-control"
onkeyup="value=value.replace(/[^\w\.\/]/ig,'')">
</div>
</div>
</div>
<div class="row" style="margin-bottom: 30px;margin-top: 10px">
<div class="col-md-12 form-label">
<button type="submit" class="btn btn-primary" style=" width: 120px;" id="buttonSubmit">
<#if (opt) == "add">add<#else>edit</#if>
</button>
<button type="button" class="btn btn-light" style="margin-left: 30px; width: 120px;"
onclick="window.history.go(-1)">取消
</button>
</div>
</div>
</form>
关键是form元素,class='form-group'样式添加,input 需要name='inputName' .这样验证样式就启作用了。
4.js添加
$(document).ready(function () {
var opt = "${opt}";
initCommon(opt);
});
/**
* 初始化验证+业务请求
* @param opt
*/
function initCommon(opt) {
formValidator();
var buttonSubmit = $('#buttonSubmit');
buttonSubmit.click(function (e) {
e.preventDefault();
//check data
var bootstrapValidator = $("form").data('bootstrapValidator');
bootstrapValidator.validate();
if(bootstrapValidator.isValid()){
//表单可以提交
buttonSubmit.attr('disabled', true);
ajaxBizData(opt);
buttonSubmit.attr('disabled', false);
}else{
//表单不可以提交
}
});
}
function formValidator() {
$('form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
inputName: {
message: '名称验证失败',
validators: {
notEmpty: {
message: '名称不能为空'
}
}
}
}
}).on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
});
}
5.效果展示