Bootstrap Validator入门案例
- Bootstrap Validator数据校验就是表单验证。友好的错误提示能增加用户体验。
- jQuery form validator for Bootstrap,从描述中我们就可以知道它至少需要jQuery、bootstrap的支持
1、导入相关组件
<%--引入bootstrap.css--%>
<link href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<%--引入BootstrapValidator.css--%>
<link href="${pageContext.request.contextPath}/bootstrapvalidator/css/bootstrapValidator.min.css" rel="stylesheet">
<%--引入jquery.js--%>
<script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script>
<%--引入Bootstrap.js--%>
<script src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
<%--引入BootstrapValidator.js--%>
<script src="${pageContext.request.contextPath}/bootstrapvalidator/js/bootstrapValidator.min.js"></script>
2、如果想对某一个字段添加验证规则,需要div(class=“form-group”)包裹,input标签必须有name值,此值为验证匹配的字段。其实就是要符合bootstrap表单结构。
<div align="center">
<form id="myForm" action="${pageContext.request.contextPath}/demo01" method="post">
<div class="form-group">
账户:<input type="text" name="username"><br>
</div>
<div class="form-group">
密码:<input type="text" name="password"><br>
</div>
<div class="form-group">
<button type="submit">提交</button>
</div>
</form>
</div>
3、使用js添加验证
<script>
$(function () {//页面加载完成
$("#myForm").bootstrapValidator({
message : "this is not a valid field",//设置提示信息
fields:{//设置要校验的字段集合
username:{
validators:{
notEmpty:{
message:"账户不能为空"
},
stringLength:{
min:6,
max:10,
message: "账户长度为6-10"
},
regexp:{
regexp: /^[a-z0-9]{6,10}$/,
message:"账户格式不正确"
}
}
},
password:{
validators:{
notEmpty:{
message:"密码不能为空"
},
stringLength:{
min:6,
max:10,
message:"密码长度为6-10"
},
regexp:{
regexp: /^[a-z0-9]{6,10}$/,
message:"密码格式不正确"
},
different:{
message:"密码不能和手机号一致",
field:"user_tel"
}
}
}
}
});
})
</script>
4、运行效果如下: