1、利用bootstrap Validator表单验证进行表单验证需要如下CSS和JS.
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrapValidator.css" />
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<script src="js/bootstrapValidator.js"></script>
具体样式找bootstrap Validator官网
2、validate规则配置
<script type="text/javascript">
$(function () {
$('form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
account: {
message: '用户名验证失败',
validators: {
stringLength: {
min: 3,
max: 15,
message: '用户名长度必须在3到15位之间'
},
regexp: {
regexp: /^[a-z0-9_-]{3,16}$/,
message: '用户名只能包含、小写、数字和下划线'
}
}
},
password: {
validators: {
stringLength: {
min: 6,
max: 18,
message: '密码长度必须在6到18位之间'
},
regexp: {
regexp: /^[a-z0-9_-]{3,16}$/,
message: '密码只能包含、小写、数字和下划线'
}
}
},
repassword: {
message: '密码无效',
validators: {
identical: {//相同
field: 'password',
message: '两次密码不一致'
},
}
},
email: {
validators: {
emailAddress: {
message: '邮箱地址格式有误'
}
}
}
}
});
});
3、对应的html页面如下
/*表单信息异步传输*/
function register_ajax(id) {
if ($(id).data('bootstrapValidator').isValid()) {
var data = $(id).serializeJSON();
var url;
if (id === "#register_form") {
url = '/api/register/';
}
$.ajax({
type: 'post',
url: url,
data: JSON.stringify(data),
contentType: "application/json",
success: function (data) {
if (data === '恭喜您,账号已成功注册') {
window.location.href = '/api/login/';
} else {
alert(data);
}
},
error: function () {
alert('Sorry,服务器可能开小差啦, 请重试!')
}
});
}
}
其他的一些用法可以参考https://www.cnblogs.com/zhangtongzct/p/5728592.html