web部分
<form class="form-horizontal" role="form" id="form" name="form" >
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">登录账户</label>
<span class="required">
*
</span>
<div class="col-md-3">
<input type="text" class="form-control input-sm" placeholder="" id="code" name="code">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">昵称</label>
<span class="required">
*
</span>
<div class="col-md-3">
<input type="text" class="form-control input-sm" placeholder="" id="name" name="name">
</div>
</div>
</div>
<div class="form-actions fluid">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green btn-primary">提交</button>
<button type="reset" class="btn default" id="resetBtn">重置</button>
</div>
</div>
</form>
JS代码
<script type="text/javascript"> $(document).ready(function() { $('#form').bootstrapValidator({ message: '这个值不能为空', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { code: { validators: { notEmpty: {}, stringLength: { min: 6, max: 50 }, threshold: 6 , //有6字符以上才发送ajax请求,(input中输入一个字符,插件会向服务器发送一次,设置限制,6字符以上才开始) remote: {//ajax验证。server result:{"valid":true or false} 向服务发送当前input name值,获得一个json数据。例表示正确:{"valid":true} url: '/user/validate_code',//验证地址 message: '账号已存在',//提示消息 delay : 1000,//每输入一个字符,就发ajax请求,服务器压力还是太大,设置2秒发送一次ajax(默认输入一个字符,提交一次,服务器压力太大) type: 'get',//请求方式 dataType: 'json', /**自定义提交数据,默认值提交当前input value * data: function(validator) { return { layerType: $('input[name=layerType]:checked').val() } }*/ } } }, name: { validators: { notEmpty: {}, stringLength: { min: 4, max: 50 } } } }, submitHandler: function (form) { success1.show(); error1.hide(); } }) .on('success.form.bv', function(e) { submitPageContent('/user/add_submit'); return false; }); $('#resetBtn').click(function() { $('#form').data('bootstrapValidator').resetForm(true); }); }); </script>
异步验证交互java代码 (remote部分)
@ResponseBody
@RequestMapping("validate_code")
public String validateCode(HttpServletRequest request) {
String code = request.getParameter("code");
User user = userImpl.getByCode(code);
if(user == null){
return "{\"valid\":true}";
}
return "{\"valid\":false}";
}
网上不少资料将json返回值写为
{\"valid\",false}
这里要注意
总之bootstrap Validator很好很强大,建议使用。