js-BootstrapValidator简单使用

时间:2022-11-06 16:10:18

本例使用版本

 <!-- 新 Bootstrap 核心 CSS 文件 -->
<link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="http://cdn.bootcss.com/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="./index.css" rel="stylesheet">
<!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script> <!-- 最新的 Bootstrap 核心 JavaScript 文件
-->
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>

默认 规则:

1.应在对应提示位置需要显示信息,故在使用某个文本等需要校验是需要

默认需要以<div class=”form-group”></div>包裹

2.使用定位到某个文本要校验时已name的值为唯一指向

<input class="form-control" />标签必须有name属性值

如下:

<form class="form-horizontal">
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email address</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="email" />
</div>
</div>
</form>

绑定规则案例

html如下

<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-5">
<input type="text" class="form-control" name="username"
data-bv-message="The username is not valid" required
data-bv-notempty-message="The username is required and cannot be empty" pattern="[a-zA-Z0-9]+"
data-bv-regexp-message="The username can only consist of alphabetical, number" />
</div>
</div>

绑定js

$(formSelector).bootstrapValidator({
/**
* 指定不验证的情况
* 值可设置为以下三种类型:
* 1、String ':disabled, :hidden, :not(:visible)'
* 2、Array 默认值 [':disabled', ':hidden', ':not(:visible)']
* 3、带回调函数
[':disabled', ':hidden', function($field, validator) {
// $field 当前验证字段dom节点
// validator 验证实例对象
// 可以再次自定义不要验证的规则
// 必须要return,return true or false;
return !$field.is(':visible');
}]
*/
excluded: [':disabled', ':hidden', ':not(:visible)'],
/**
* 指定验证后验证字段的提示字体图标。(默认是bootstrap风格)
* Bootstrap 版本 >= 3.1.0
* 也可以使用任何自定义风格,只要引入好相关的字体文件即可
* 默认样式
.form-horizontal .has-feedback .form-control-feedback {
top: 0;
right: 15px;
}
* 自定义该样式覆盖默认样式
.form-horizontal .has-feedback .form-control-feedback {
top: 0;
right: -15px;
}
.form-horizontal .has-feedback .input-group .form-control-feedback {
top: 0;
right: -30px;
}
*/
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
/**
* 生效规则(三选一)
* enabled 字段值有变化就触发验证
* disabled,submitted 当点击提交时验证并展示错误信息
*/
live: 'enabled',
/**
* 为每个字段指定通用错误提示语
*/
message: 'This value is not valid',
/**
* 指定提交的按钮,例如:'.submitBtn' '#submitBtn'
* 当表单验证不通过时,该按钮为disabled
*/
submitButtons: 'button[type="submit"]',
/**
* submitHandler: function(validator, form, submitButton) {
* //validator: 表单验证实例对象
* //form jq对象 指定表单对象
* //submitButton jq对象 指定提交按钮的对象
* }
* 在ajax提交表单时很实用
* submitHandler: function(validator, form, submitButton) {
// 实用ajax提交表单
$.post(form.attr('action'), form.serialize(), function(result) {
// .自定义回调逻辑
}, 'json');
}
*
*/
submitHandler: null,
/**
* 为每个字段设置统一触发验证方式(也可在fields中为每个字段单独定义),默认是live配置的方式,数据改变就改变
* 也可以指定一个或多个(多个空格隔开) 'focus blur keyup'
*/
trigger: null,
/**
* Number类型 为每个字段设置统一的开始验证情况,当输入字符大于等于设置的数值后才实时触发验证
*/
threshold: null,
/**
* 表单域配置
*/
fields: {
//多个重复
<fieldName>: {
//隐藏或显示 该字段的验证
enabled: true,
//错误提示信息
message: 'This value is not valid',
/**
* 定义错误提示位置 值为CSS选择器设置方式
* 例如:'#firstNameMeg' '.lastNameMeg' '[data-stripe="exp-month"]'
*/
container: null,
/**
* 定义验证的节点,CSS选择器设置方式,可不必须是name值。
* 若是id,class, name属性,<fieldName>为该属性值
* 若是其他属性值且有中划线链接,<fieldName>转换为驼峰格式 selector: '[data-stripe="exp-month"]' => expMonth
*/
selector: null,
/**
* 定义触发验证方式(也可在fields中为每个字段单独定义),默认是live配置的方式,数据改变就改变
* 也可以指定一个或多个(多个空格隔开) 'focus blur keyup'
*/
trigger: null,
// 定义每个验证规则
validators: {
//多个重复
//官方默认验证参照 http://bv.doc.javake.cn/validators/
// 注:使用默认前提是引入了bootstrapValidator-all.js
// 若引入bootstrapValidator.js没有提供常用验证规则,需自定义验证规则哦
<validatorName>: <validatorOptions>
}
}
}
});

自定义校验规则如下

(function($) {
//自定义表单验证规则
$.fn.bootstrapValidator.validators = {
<validatorName> : {
/**
* @param {BootstrapValidator} 表单验证实例对象
* @param {jQuery} $field jQuery 对象
* @param {Object} 表单验证配置项值
* @returns {boolean}
*/
validate: function(validator, $field, options) {
// 表单输入的值
// var value = $field.val(); //options为<validatorOptions>对象,直接.获取需要的值 // 返回true/false
//也可返回{ valid : true/false, message: 'XXXX'}
return reg.test( $field.val() ); }
},
};
}(window.jQuery));

其他重要事件

1、重置某一单一验证字段验证规则

$(formName).data(“bootstrapValidator”).updateStatus("fieldName",  "NOT_VALIDATED",  null );

2、重置表单所有验证规则

$(formName).data("bootstrapValidator").resetForm();

3、手动触发表单验证

//触发全部验证
$(formName).data(“bootstrapValidator”).validate();
//触发指定字段的验证
$(formName).data(“bootstrapValidator”).validate('fieldName');

4、获取当前表单验证状态

// flag = true/false
var flag = $(formName).data(“bootstrapValidator”).isValid();

5、根据指定字段名称获取验证对象

// element = jq对象 / null
var element = $(formName).data(“bootstrapValidator”).getFieldElements('fieldName');

手动提交按钮校验

$("buttonName").on("click", function(){
//获取表单对象
var bootstrapValidator = form.data('bootstrapValidator');
//手动触发验证
bootstrapValidator.validate();
if(bootstrapValidator.isValid()){
//表单提交的方法、比如ajax提交
}
});

当提交按钮的[type=”submit”]时 
会在success之前自动触发表单验证

var bootstrapValidator = form.data('bootstrapValidator');
bootstrapValidator.on('success.form.bv', function (e) {
e.preventDefault();
//提交逻辑
});

各种校验规则

             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: '请输入正确的邀请码(包含数字字母)'
}
}
},

另完整远程校验

$(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...
});
});
});