BootstrapValidator,簡單而實用的表單驗證插件

Bootstrap是現在非常流行的一款前端框架,這篇來介紹一款基於Bootstrap的驗證插件BootstrapValidator。

先來看一下效果圖(樣式是不是還不錯O(∩_∩)O哈哈~)。

Bootstrapvalidator下載地址:https://github.com/nghuuphuoc/bootstrapvalidator/ 

引入對應的CSS和JS

<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrapValidator.css" />
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<script src="js/bootstrapValidator.js"></script>

添加驗證規則

使用HTML添加驗證。

對某一個標籤添加驗證規則,需要放在<div class="form-group"></div>標籤中,input標籤必須有name屬性值,此值爲驗證匹配的字段。其實就是要符合bootstrap表單結構。

<div class="form-group">
    <label class="col-md-2 control-label">學號</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="stuNumber" data-bv-notempty="true" data-bv-notempty-message="用戶名不能爲空" />
    </div>
</div>

初始化bootstrapValidator。

<script type="text/javascript">
$('form').bootstrapValidator({
    //默認提示
    message: 'This value is not valid',
    // 表單框裏右側的icon
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'      
    },
    submitHandler: function (validator, form, submitButton) {
        // 表單提交成功時會調用此方法
        // validator: 表單驗證實例對象
        // form  jq對象  指定表單對象
        // submitButton  jq對象  指定提交按鈕的對象
    }
});
</script>

效果圖。

使用data-bv-notempty 和 data-bv-notempty-message屬性就可以簡單進行非空驗證。data-bv-notempty 有值就進行非空驗證,data-bv-notempty-message 中的值爲提示消息。

使用JS添加驗證

HTML樣式代碼。

<div class="form-group">
    <label class="col-md-2 control-label">姓名</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="name" />
    </div>
</div>
<div class="form-group">
    <label class="col-md-2 control-label">年齡</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="age" />
    </div>
</div>
<div class="form-group">
    <label class="col-md-2 control-label">電話</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="phoneNumber" />
    </div>
</div>
<div class="form-group">
    <label class="col-md-2 control-label">Email</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="email" />
    </div>
</div>
<div class="form-group">
    <label class="col-md-2 control-label">密碼</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="pwd" />
    </div>
</div>
<div class="form-group">
    <label class="col-md-2 control-label">確定密碼</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="pwd1" />
    </div>
</div>

JS驗證代碼,其中fields屬性中的值,需要和HTML標籤中的name值一樣,確定給那個標籤添加驗證。

<script type="text/javascript">
    $('form').bootstrapValidator({
        //默認提示
        message: 'This value is not valid',
        // 表單框裏右側的icon
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        submitHandler: function (validator, form, submitButton) {
            // 表單提交成功時會調用此方法
            // validator: 表單驗證實例對象
            // form  jq對象  指定表單對象
            // submitButton  jq對象  指定提交按鈕的對象
        },
        fields: {
            username: {
                message: '用戶名驗證失敗',
                validators: {
                    notEmpty: {     //不能爲空
                        message: '用戶名不能爲空'
                    },
                    remote: {   //後臺驗證,比如查詢用戶名是否存在
                        url: 'student/verifyUsername',
                        message: '此用戶名已存在'
                    }
                }
            },
            name: {
                message: '姓名驗證失敗',
                validators: {
                    notEmpty: {
                        message: '姓名不能爲空'
                    }
                }
            },
            age: {
                message: '年齡驗證失敗',
                validators: {
                    notEmpty: {
                        message: '年齡不能爲空'
                    },
                    numeric: {
                        message: '請填寫數字'
                    }
                }
            },
            phoneNumber: {
                message: '電話號驗證失敗',
                validators: {
                    notEmpty: {
                        message: '電話號不能爲空'
                    },
                    regexp: {   //正則驗證
                        regexp: /^1\d{10}$/,
                        message: '請輸入正確的電話號'
                    }
                }
            },
            email: {
                message: 'Email驗證失敗',
                validators: {
                    notEmpty: {
                        message: 'Email不能爲空'
                    },
                    emailAddress: {     //驗證email地址
                        message: '不是正確的email地址'
                    }
                }
            },
            pwd: {
                notEmpty: {
                    message: '密碼不能爲空'
                },
                stringLength: {     //檢測長度
                    min: 4,
                    max: 15,
                    message: '用戶名需要在4~15個字符'
                }
            },
            pwd1: {
                message: '密碼驗證失敗',
                validators: {
                    notEmpty: {
                        message: '密碼不能爲空'
                    },
                    identical: {    //與指定控件內容比較是否相同,比如兩次密碼不一致
                        field: 'pwd',//指定控件name
                        message: '兩次密碼不一致'
                    }
                }
            }
        }
    });
</script>

效果如下。

AJAX後臺交互驗證,驗證用戶名是否存在。

<div class="form-group">
    <label class="col-md-2 control-label">用戶名</label>
    <div class="col-md-6">
        <input type="text" class="form-control" name="username" />
    </div>
</div>

<script type="text/javascript">
$('form').bootstrapValidator({
    //默認提示
    message: 'This value is not valid',
    // 表單框裏右側的icon
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'      
    },
    submitHandler: function (validator, form, submitButton) {
        // 表單提交成功時會調用此方法
        // validator: 表單驗證實例對象
        // form  jq對象  指定表單對象
        // submitButton  jq對象  指定提交按鈕的對象
    },
    fields: {
        username: {
            message: '用戶名驗證失敗',
            validators: {
                notEmpty: {     //不能爲空
                    message: '用戶名不能爲空'
                },
                remote: {   //後臺驗證,比如查詢用戶名是否存在
                    url: 'student/verifyUsername',
                    message: '此用戶名已存在'
                }
           }
        }
    }
});
</script>

後臺驗證返回格式必須爲{“valid”, true or false} 的json數據格式。後臺verifyUsername驗證判斷方法。

@RequestMapping(value="/verifyUsername")
@ResponseBody
public Map verifyUsername(String username){
    Student stu = studentService.findByUsername(username);
    Map map = new HashMap();
    if (stu == null) {
        map.put("valid", true);
    }else{
        map.put("valid", false);
    }
    return map;
}

效果如下。

下面是幾個比較常見的驗證規則。

  1. notEmpty:非空驗證;
  2. stringLength:字符串長度驗證;
  3. regexp:正則表達式驗證;
  4. emailAddress:郵箱地址驗證(都不用我們去寫郵箱的正則了~~)
  5. base64:64位編碼驗證;
  6. between:驗證輸入值必須在某一個範圍值以內,比如大於10小於100;
  7. creditCard:身份證驗證;
  8. date:日期驗證;
  9. ip:IP地址驗證;
  10. numeric:數值驗證;
  11. url:url驗證;
  12. callback:自定義驗證

Form表單的提交

關於提交,可以直接用form表單提交即可。

<div class="form-group">
    <div class="col-md-6 col-md-offset-2">
        <button id="btn" type="submit" class="btn btn-primary">提交</button>
    </div>
</div>

也可以通過AJAX提交,提交按鈕代碼和form表單的提交按鈕代碼一樣,通過id選中按鈕綁定點擊事件提交。

$("#btn").click(function () {   //非submit按鈕點擊後進行驗證,如果是submit則無需此句直接驗證
    $("form").bootstrapValidator('validate');   //提交驗證
    if ($("form").data('bootstrapValidator').isValid()) {   //獲取驗證結果,如果成功,執行下面代碼
        alert("yes");   //驗證成功後的操作,如ajax
    }
});

效果圖,這裏驗證通過後通過彈框提示的,方法中可以寫AJAX提交代碼。

頁面完整代碼。

<meta charset="UTF-8">
<form action="" class="form-horizontal">
    <div class="form-group">
        <label class="col-md-2 control-label">學號</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="stuNumber" data-bv-notempty="true" data-bv-notempty-message="用戶名不能爲空" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">用戶名</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="username" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">姓名</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="name" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">年齡</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="age" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">電話</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="phoneNumber" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Email</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="email" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">密碼</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="pwd" />
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">確定密碼</label>
        <div class="col-md-6">
            <input type="text" class="form-control" name="pwd1" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-6 col-md-offset-2">
            <button id="btn" type="submit" class="btn btn-primary">提交</button>
        </div>
    </div>
</form>

<script type="text/javascript">
    $(function () {
        $('form').bootstrapValidator({
            //默認提示
            message: 'This value is not valid',
            // 表單框裏右側的icon
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            submitHandler: function (validator, form, submitButton) {
                // 表單提交成功時會調用此方法
                // validator: 表單驗證實例對象
                // form  jq對象  指定表單對象
                // submitButton  jq對象  指定提交按鈕的對象
            },
            fields: {
                username: {
                    message: '用戶名驗證失敗',
                    validators: {
                        notEmpty: {     //不能爲空
                            message: '用戶名不能爲空'
                        },
                        remote: {   //後臺驗證,比如查詢用戶名是否存在
                            url: 'student/verifyUsername',
                            message: '此用戶名已存在'
                        }
                    }
                },
                name: {
                    message: '姓名驗證失敗',
                    validators: {
                        notEmpty: {
                            message: '姓名不能爲空'
                        }
                    }
                },
                age: {
                    message: '年齡驗證失敗',
                    validators: {
                        notEmpty: {
                            message: '年齡不能爲空'
                        },
                        numeric: {
                            message: '請填寫數字'
                        }
                    }
                },
                phoneNumber: {
                    message: '電話號驗證失敗',
                    validators: {
                        notEmpty: {
                            message: '電話號不能爲空'
                        },
                        regexp: {   //正則驗證
                            regexp: /^1\d{10}$/,
                            message: '請輸入正確的電話號'
                        }
                    }
                },
                email: {
                    message: 'Email驗證失敗',
                    validators: {
                        notEmpty: {
                            message: 'Email不能爲空'
                        },
                        emailAddress: {     //驗證email地址
                            message: '不是正確的email地址'
                        }
                    }
                },
                pwd: {
                    notEmpty: {
                        message: '密碼不能爲空'
                    },
                    stringLength: {     //檢測長度
                        min: 4,
                        max: 15,
                        message: '用戶名需要在4~15個字符'
                    }
                },
                pwd1: {
                    message: '密碼驗證失敗',
                    validators: {
                        notEmpty: {
                            message: '密碼不能爲空'
                        },
                        identical: {    //與指定控件內容比較是否相同,比如兩次密碼不一致
                            field: 'pwd',//指定控件name
                            message: '兩次密碼不一致'
                        }
                    }
                }
            }
        });

        $("#btn").click(function () {   //非submit按鈕點擊後進行驗證,如果是submit則無需此句直接驗證
            $("form").bootstrapValidator('validate');   //提交驗證
            if ($("form").data('bootstrapValidator').isValid()) {   //獲取驗證結果,如果成功,執行下面代碼
                alert("yes");   //驗證成功後的操作,如ajax
            }
        });
    })
</script>

到這裏,BootstrapValidator驗證插件的方法已經寫的很全面了。不足地方歡迎大家下方留言指出!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章