使用bootstrapvalidator的remote驗證經驗

Franson發表於2016-06-24

這裡需要說一下,bootstrapvalidator的幫助文件寫的比較簡單,對於remote驗證器的說明更是如此,在經歷多方測試之後才明白如何使用這個驗證器。

一個典型的ajax驗證程式碼如下:

服務端驗證程式碼(使用spring mvc)如下:

/*
     * 返回String型別的結果
     * 檢查使用者名稱的合法性,如果使用者已經存在,返回false,否則返回true(返回json資料,格式為{"valid",true})
     */
    @RequestMapping(value = "/checkNameExistsMethod1", produces = "application/json;charset=UTF-8")
    public @ResponseBody
    String checkNameValidMethod1(@RequestParam String name) {
        boolean result = true;
        List<Employee> lstEmployees = employeeService.getAllEmployees();
        for (Employee employee : lstEmployees) {
            if (employee.getName().equals(name)) {
                result = false;
                break;
            }
        }
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }

這裡需要說明的是bootstrap的remote驗證器需要的返回結果一定是json格式的資料 :

{"valid":false} //表示不合法,驗證不通過
{"valid":true} //表示合法,驗證通過

如果返回任何其他的值,頁面驗證將獲取不到驗證結果導致無法驗證。

附一段完整的遠端remote驗證的程式碼加說明:

$(function(){/* 文件載入,執行一個函式*/
     $('#defaultForm').bootstrapValidator({
         message: 'This value is not valid',
         feedbackIcons: {/*input狀態樣式圖片*/
             valid: 'glyphicon glyphicon-ok',
             invalid: 'glyphicon glyphicon-remove',
             validating: 'glyphicon glyphicon-refresh'
         },
         fields: {/*驗證:規則*/
             username: {//驗證input項:驗證規則
                 message: 'The username is not valid',
                
                 validators: {
                     notEmpty: {//非空驗證:提示訊息
                         message: '使用者名稱不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '使用者名稱長度必須在6到30之間'
                     },
                     threshold :  6 , //有6字元以上才傳送ajax請求,(input中輸入一個字元,外掛會向伺服器傳送一次,設定限制,6字元以上才開始)
                     remote: {//ajax驗證。server result:{"valid",true or false} 向服務傳送當前input name值,獲得一個json資料。例表示正確:{"valid",true}  
                         url: 'exist2.do',//驗證地址
                         message: '使用者已存在',//提示訊息
                         delay :  2000,//每輸入一個字元,就發ajax請求,伺服器壓力還是太大,設定2秒傳送一次ajax(預設輸入一個字元,提交一次,伺服器壓力太大)
                         type: 'POST'//請求方式
                         /**自定義提交資料,預設值提交當前input value
                          *  data: function(validator) {
                               return {
                                   password: $('[name="passwordNameAttributeInYourForm"]').val(),
                                   whatever: $('[name="whateverNameAttributeInYourForm"]').val()
                               };
                            }
                          */
                     },
                     regexp: {
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: '使用者名稱由數字字母下劃線和.組成'
                     }
                 }
             },
             password: {
                 message:'密碼無效',
                 validators: {
                     notEmpty: {
                         message: '密碼不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '使用者名稱長度必須在6到30之間'
                     },
                     identical: {//相同
                         field: 'password', //需要進行比較的input name值
                         message: '兩次密碼不一致'
                     },
                     different: {//不能和使用者名稱相同
                         field: 'username',//需要進行比較的input name值
                         message: '不能和使用者名稱相同'
                     },
                     regexp: {
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: 'The username can only consist of alphabetical, number, dot and underscore'
                     }
                 }
             },
             repassword: {
                 message: '密碼無效',
                 validators: {
                     notEmpty: {
                         message: '使用者名稱不能為空'
                     },
                     stringLength: {
                         min: 6,
                         max: 30,
                         message: '使用者名稱長度必須在6到30之間'
                     },
                     identical: {//相同
                         field: 'password',
                         message: '兩次密碼不一致'
                     },
                     different: {//不能和使用者名稱相同
                         field: 'username',
                         message: '不能和使用者名稱相同'
                     },
                     regexp: {//匹配規則
                         regexp: /^[a-zA-Z0-9_\.]+$/,
                         message: 'The username can only consist of alphabetical, number, dot and underscore'
                     }
                 }
             },
             email: {
                 validators: {
                     notEmpty: {
                         message: '郵件不能為空'
                     },
                     emailAddress: {
                         message: '請輸入正確的郵件地址如:123@qq.com'
                     }
                 }
             },
             phone: {
                 message: 'The phone is not valid',
                 validators: {
                     notEmpty: {
                         message: '手機號碼不能為空'
                     },
                     stringLength: {
                         min: 11,
                         max: 11,
                         message: '請輸入11位手機號碼'
                     },
                     regexp: {
                         regexp: /^1[3|5|8]{1}[0-9]{9}$/,
                         message: '請輸入正確的手機號碼'
                     }
                 }
             },
             invite: {
                 message: '邀請碼',
                 validators: {
                     notEmpty: {
                         message: '邀請碼不能為空'
                     },
                     stringLength: {
                         min: 8,
                         max: 8,
                         message: '請輸入正確長度的邀請碼'
                     },
                     regexp: {
                         regexp: /^[\w]{8}$/,
                         message: '請輸入正確的邀請碼(包含數字字母)'
                     }
                 }
             },
         }
     })
     .on('success.form.bv', function(e) {//點選提交之後
         // Prevent form submission
         e.preventDefault();

         // Get the form instance
         var $form = $(e.target);

         // Get the BootstrapValidator instance
         var bv = $form.data('bootstrapValidator');

         // Use Ajax to submit form data 提交至form標籤中的action,result自定義
         $.post($form.attr('action'), $form.serialize(), function(result) {
//do something...
});
     });
});

 

 

相關文章