Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解


Posted in Javascript onMarch 29, 2020

本文实例讲述了Bootstrap简单实用的表单验证插件BootstrapValidator用法。分享给大家供大家参考,具体如下:

Bootstrap是现在非常流行的一款前端框架,这篇来介绍一款基于Bootstrap的验证插件BootstrapValidator。

先来看一下效果图(样式是不是还不错O(∩_∩)O哈哈~)。

Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解

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

引入对应的CSS和JS

<link rel="stylesheet" type="text/css" href="css/bootstrap.css" rel="external nofollow" />
<link rel="stylesheet" type="text/css" href="css/bootstrapValidator.css" rel="external nofollow" />
<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>

效果图。

Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解

使用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>

效果如下。

Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解

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;
}

效果如下。

Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解

下面是几个比较常见的验证规则。

  • notEmpty:非空验证;
  • stringLength:字符串长度验证;
  • regexp:正则表达式验证;
  • emailAddress:邮箱地址验证(都不用我们去写邮箱的正则了~~)
  • base64:64位编码验证;
  • between:验证输入值必须在某一个范围值以内,比如大于10小于100;
  • creditCard:身份证验证;
  • date:日期验证;
  • ip:IP地址验证;
  • numeric:数值验证;
  • url:url验证;
  • 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提交代码。

Bootstrap简单实用的表单验证插件BootstrapValidator用法实例详解

页面完整代码。

<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验证插件的方法已经写的很全面了。不足地方欢迎大家下方留言指出!

可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun测试上述代码运行效果。

Javascript 相关文章推荐
javascript整除实现代码
Nov 23 Javascript
JS截取url中问号后面参数的值信息
Apr 29 Javascript
jquery插件之定时查询待处理任务数量
May 01 Javascript
jQuery实现table中的tr上下移动并保持序号不变的实例代码
Jul 11 Javascript
ECMAscript 变量作用域总结概括
Aug 18 Javascript
React Native日期时间选择组件的示例代码
Apr 27 Javascript
js使用formData实现批量上传
Mar 27 Javascript
Koa从零搭建到Api实现项目的搭建方法
Jul 30 Javascript
扫微信小程序码实现网站登陆实现解析
Aug 20 Javascript
javascript 关于赋值、浅拷贝、深拷贝的个人理解
Nov 01 Javascript
详解node.js 事件循环
Jul 22 Javascript
ES6 十大特性简介
Dec 09 Javascript
JS实现滑动拼图验证功能完整示例
Mar 29 #Javascript
json_decode 索引为数字时自动排序问题解决方法
Mar 28 #Javascript
JS中FormData类实现文件上传
Mar 27 #Javascript
JS中FileReader类实现文件上传及时预览功能
Mar 27 #Javascript
js、jquery实现列表模糊搜索功能过程解析
Mar 27 #jQuery
开发Node CLI构建微信小程序脚手架的示例
Mar 27 #Javascript
微信小程序间使用navigator跳转传值问题实例分析
Mar 27 #Javascript
You might like
zen cart新进商品的随机排序修改方法
2010/09/10 PHP
php入门学习知识点一 PHP与MYSql连接与查询
2011/07/14 PHP
php安全开发 添加随机字符串验证,防止伪造跨站请求
2013/02/14 PHP
PHP模板引擎Smarty中变量的使用方法示例
2016/04/11 PHP
php中关于长度计算容易混淆的问题分析
2016/05/27 PHP
Yii2框架RESTful API 格式化响应,授权认证和速率限制三部分详解
2016/11/10 PHP
JavaScript.The.Good.Parts阅读笔记(二)作用域&amp;闭包&amp;减缓全局空间污染
2010/11/16 Javascript
node.js中的fs.appendFileSync方法使用说明
2014/12/17 Javascript
javascript中replace( )方法的使用
2015/04/24 Javascript
js判断日期时间有效性的方法
2015/10/24 Javascript
Bootstrap中的fileinput 多图片上传及编辑功能
2016/09/05 Javascript
微信小程序 animation API详解及实例代码
2016/10/08 Javascript
jQuery基于ajax操作json数据简单示例
2017/01/05 Javascript
vue中用动态组件实现选项卡切换效果
2017/03/25 Javascript
vue 怎么创建组件及组件使用方法
2017/07/27 Javascript
微信小程序引用iconfont图标的方法
2018/10/22 Javascript
微信小程序实现卡片左右滑动效果的示例代码
2019/05/01 Javascript
小程序实现悬浮搜索框
2019/07/12 Javascript
npm全局环境变量配置详解
2020/12/15 Javascript
[02:09]2018DOTA2亚洲邀请赛TNC赛前采访
2018/04/04 DOTA
[02:40]2018年度DOTA2最佳新人-完美盛典
2018/12/16 DOTA
Python单元测试框架unittest简明使用实例
2015/04/13 Python
Python 3.x 新特性及10大变化
2015/06/12 Python
OpenCV中VideoCapture类的使用详解
2020/02/14 Python
Python读取VOC中的xml目标框实例
2020/03/10 Python
Selenium 滚动页面至元素可见的方法
2020/03/18 Python
pycharm远程连接vagrant虚拟机中mariadb数据库
2020/06/05 Python
Python2.x与3​​.x版本有哪些区别
2020/07/09 Python
全球领先的各类汽车配件零售商:Advance Auto Parts
2016/08/26 全球购物
adidas美国官网:adidas US
2016/09/21 全球购物
技术总监管理岗位职责
2014/03/09 职场文书
企业员工爱岗敬业演讲稿
2014/08/26 职场文书
2015年幼儿园教研活动总结
2015/03/25 职场文书
二审代理词范文
2015/05/25 职场文书
MySQL 逻辑备份与恢复测试的相关总结
2021/05/14 MySQL
vue3使用vuedraggable实现拖拽功能
2022/04/06 Vue.js