使用bootstrapValidator插件校验表单。
1.html中编写相应的表单元素,需要含有一个<button type="submit" >登录</button>
。
2.引入bootstrap和bootstrap-validator对应的css和js文件。
3.初始化插件:
//初始化bootstrap-validator插件
$('#formId').bootstrapValidator({
// 配置不同状态下显示的图标
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
// 需要校验的表单元素 通过name
fields: {
username: { //配置username
validators: {
notEmpty: { // 用户输入为空时
message: '用户名不能为空'
},
callback: { //发送ajax,后端验证后
message: '用户名不存在'
}
}
},
password: { //配置password
validators: {
notEmpty: { // 用户输入为空时
message: '密码不能为空'
},
stringLength: { // 输入的长度限制
min: 6,
max: 18,
message: '密码长度必须在6到18位之间'
},
callback: { //发送ajax,后端验证后
message: '密码错误'
}
}
}
}
}).on('success.form.bv', function(e){
// 校验通过后,点击submit按钮,应该屏蔽默认行为,直接发ajax进行后端验证
e.preventDefault()
// 获取表单以及表单数据
var $form = $(e.target)
var serialize = $form.serialize()
$.ajax({
url: '/path/to/api',
type: 'post',
data: serialize,
dataType: 'json',
success: function(res){
//更改input状态 为VALIDATING 校验中
//INVALID 校验失败, VALIDATING 校验中, VALID 成功,NOT_VALIDATED 还没校验
//获取校验组件,使用其.updateStatus()方法,传3个参数:校验哪个input,改成什么状态,使用哪个校验规则
$form.data('bootstrapValidator').updateStatus('username','VALIDATING')
$form.data('bootstrapValidator').updateStatus('password','VALIDATING')
if(res.success == true){
location.href = '/path/to/mainpage'
}else if(res.error == xxx){
// 用户名错误
// 根据具体情况,更改input验证状态
$form.data('bootstrapValidator').updateStatus('username','INVALID','callback' )
$form.data('bootstrapValidator').updateStatus('password','VALID')
}else if(res.error == xxx){
// 密码错误
// 根据具体情况,更改input校验状态
$form.data('bootstrapValidator').updateStatus('username','VALID')
$form.data('bootstrapValidator').updateStatus('password','INVALID','callback' )
}
}
})
})
`