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