目的:
试了一下远程验证,试了好几次,得出小结,可以记录下,提醒以防绕路。
----------------直接贴图,省事明了----------------
1.引用js
2.demo的html
<form action="/user/save" method="post" class="form form-horizontal" id="form-member-add">
<div class="row cl">
<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>用户名:</label>
<div class="formControls col-xs-8 col-sm-9">
<input type="text" class="input-text" placeholder="XXX" id="username" name="username">
</div>
</div>
</form>
<script type="text/javascript" src="lib/jquery.validation/1.14.0/jquery.validate.js"></script>
<script type="text/javascript" src="lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="lib/jquery.validation/1.14.0/messages_zh.js"></script>
<script type="text/javascript">
$(function(){
$("#form-member-add").validate({
rules: {
username: {
required: true,
minlength: 2,
maxlength: 8,
remote: {
url: '/verifyUsername',
type: 'post',
data: {
"name": function () {
return $("input[name='username']").val();
}
}
}
}
},
messages: {
username: {
required: '请输入用户名',
remote: '用户已存在'
}
},
onkeyup: false,
focusCleanup: true,
success: "valid",
submitHandler: function (form) {
$(form).ajaxSubmit(function (data) {});
}
});
});
</script>
⚠️注意:这个地方很多人都会出现不行的问题,所以,注意第24行的data里面的“name”,要和后台程序接口的参数名一致,url后面不用加参数,js会自己拼接请求。
3.demo程序接口
@PostMapping("/verifyUsername")
@ResponseBody
public boolean verifyUsername(@RequestParam(value = "name",defaultValue = "") String name){
if(StringUtils.isNotEmpty(name)) {
return userService.verifyUsername(name);
} return false;
}
⚠️注意:js只接受true和false
4.结果
只要第2条“注意”的内容知道了,基本上也就没什么问题了。