html:javascript
1 <div class="form-group"> 2 <label for="username" class="control-label col-md-3 col-sm-4">帳號</label> 3 <div class="col-md-9 col-sm-8"> 4 <div class="input-group"> 5 <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span> 6 <input type="text" class="form-control" id="username" name="username" placeholder="請輸入暱稱"/> 7 </div> 8 </div> 9 </div>
js:html
1 <script type="text/javascript"> 2 $(function () { 3 //alert(123) 4 $("#regist_form").bootstrapValidator({ 5 live: 'enabled', //驗證時機,enabled是內容有變化就驗證(默認),disabled和submitted是提交再驗證 6 excluded: [':disabled', ':hidden', ':not(:visible)', ':file'], //排除無需驗證的控件,好比被禁用的或者被隱藏的 7 submitButtons: '#reg-btn', //指定提交按鈕,若是驗證失敗則變成disabled,按鈕變灰色 8 message: '通用的驗證失敗消息', //好像歷來沒出現過 9 feedbackIcons: { //根據驗證結果顯示的各類圖標 10 valid: 'glyphicon glyphicon-ok', 11 invalid: 'glyphicon glyphicon-remove', //小叉號 12 validating: 'glyphicon glyphicon-refresh' 13 }, 14 fields: { 15 username: { 16 verbose: false, //表明驗證按順序驗證。驗證成功纔會下一個(驗證成功纔會發最後一個remote遠程驗證) 17 validators: { 18 notEmpty: { 19 message: '帳號不能爲空' 20 }, 21 stringLength: { 22 min: 6, 23 max: 30, 24 message: '帳號長度必須在6到30之間' 25 }, 26 threshold: 6,//有6字符以上才發送ajax請求 27 28 remote: { //ajax驗證。server result:{"valid",true or false} (返回前臺類型) 29 url: "stu-exist", 30 message: '用戶名已存在,請從新輸入', 31 delay: 500, //ajax刷新的時間是0.5秒一次 32 type: 'POST', 33 //自定義提交數據,默認值提交當前input value 34 /*data: function (validator) { 35 return { 36 userName: $("input[name=userName]").val(), 37 //method: "stuIsExist" //UserServlet判斷調用方法關鍵字。 38 39 }; 40 }*/ 41 }, 42 } 43 }, 44 } 45 46 }); 47 }) 48 </script>
StuService:java
1 //驗證帳號是否存在(用戶註冊) 2 Boolean stuIsExist(String username);
StuServiceImpl:ajax
1 /** 2 * @Description //驗證帳號是否存在 3 * @Date 2019-04-01 17:39 4 * @Param [username] 5 * @return java.lang.Boolean 6 **/ 7 @Override 8 public Boolean stuIsExist(String username) { 9 10 UserExample userExample = new UserExample(); 11 UserExample.Criteria criteria = userExample.createCriteria(); 12 criteria.andUsernameEqualTo(username); 13 List<User> userList = userMapper.selectByExample(userExample); 14 if (userList.isEmpty()) { 15 return true; 16 } else { 17 return false; 18 } 19 20 }
RegisterController.java:bootstrap
1 /** 2 * @Description //驗證帳號是否存在 3 * @Date 2019-04-01 17:43 4 * @Param [username] 5 * @return java.util.Map<java.lang.String,java.lang.Boolean> 6 **/ 7 @PostMapping("stu-exist") 8 @ResponseBody 9 public Map<String,Boolean> stuIsExist(String username){ 10 Boolean stuIsExist = stuService.stuIsExist(username); 11 Map<String,Boolean> map = new HashMap<String,Boolean>(); 12 13 //map.put("valid",true); 14 if (stuIsExist){ 15 map.put("valid",true); 16 }else { 17 map.put("valid",false); 18 } 19 20 System.out.println(username+map); 21 return map; 22 }