Bootstrap 表單驗證 BootstrapValidator
做網站難免就會遇到需要驗證表單的時候,因為要自己寫驗證很麻煩(也不用每次都花力氣),所以就有很多人寫好驗證的 plugin 供人使用,這陣子以來 bootstrap 很流行,最近也找到了用 bootstrap 為基礎的Validator BootstrapValidator,用起來也很簡單,有興趣就試試吧。
當然也是先把東西放到網頁上。
然後參考網站上的寫法。
或是直接寫在 html 裡就可以執行了。
當然也是先把東西放到網頁上。
- <link rel="stylesheet" href="/path/to/bootstrap/css/bootstrap.css"/>
- <link rel="stylesheet" href="/path/to/dist/css/bootstrapValidator.min.css"/>
- <script type="text/javascript" src="/path/to/jquery/jquery-1.10.2.min.js"></script>
- <script type="text/javascript" src="/path/to/bootstrap/js/bootstrap.min.js"></script>
然後參考網站上的寫法。
- $('.registerForm').bootstrapValidator({
- message: 'This value is not valid',
- feedbackIcons: {
- valid: 'glyphicon glyphicon-ok',
- invalid: 'glyphicon glyphicon-remove',
- validating: 'glyphicon glyphicon-refresh'
- },
- fields: {
- username: {
- message: 'The username is not valid',
- validators: {
- notEmpty: {
- message: 'The username is required and cannot be empty'
- },
- stringLength: {
- min: 6,
- max: 30,
- message: 'The username must be more than 6 and less than 30 characters long'
- },
- regexp: {
- regexp: /^[a-zA-Z0-9_]+$/,
- message: 'The username can only consist of alphabetical, number and underscore'
- }
- }
- },
- email: {
- validators: {
- notEmpty: {
- message: 'The email is required and cannot be empty'
- },
- emailAddress: {
- message: 'The input is not a valid email address'
- }
- }
- }
- }
- });
或是直接寫在 html 裡就可以執行了。
- <div class="form-group">
- <label class="col-lg-3 control-label">Full name</label>
- <div class="col-lg-4">
- <input type="text" class="form-control" name="firstName" placeholder="First name"
- data-bv-notempty="true"
- data-bv-notempty-message="The first name is required and cannot be empty" />
- </div>
- <div class="col-lg-4">
- <input type="text" class="form-control" name="lastName" placeholder="Last name"
- data-bv-notempty="true"
- data-bv-notempty-message="The last name is required and cannot be empty" />
- </div>
- </div>
留言