表单验证插件--formvalidation

时间:2023-03-08 20:33:21
表单验证插件--formvalidation

表单验证是一个非常基础的功能,当你的表单项少的时候,可以自己写验证,但是当你的表单有很多的时候,就需要一些验证的插件。今天介绍一款很好用的表单验证插件,formvalidation。其前身叫做bootstrapValidator.

官网:http://formvalidation.io/

下载:目前的最新版本是收费的,但是我们可以下载之前的版本。下载地址:http://down.htmleaf.com/1505/201505101833.zip

下载之后,解压,整个文件夹里面除了最基本的js和css,还包含了很多实例,有兴趣的可以自己去看看。接下来简要介绍一下它的用法。

1.导入包

css:

<link rel="stylesheet"
href="./static/formvalidation/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
href="./static/formvalidation/dist/css/formValidation.css">

js:

<script type="text/javascript" src="./static/formvalidation/vendor/jquery/jquery.min.js"></script>
<script type="text/javascript" src="./static/formvalidation/vendor/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="./static/formvalidation/dist/js/formValidation.js"></script>
<script type="text/javascript" src="./static/formvalidation/dist/js/framework/bootstrap.js"></script>
<script type="text/javascript" src="./static/formvalidation/dist/js/language/zh_CN.js"></script>

需要注意的是,即便你已经在项目中导入了bootstrap.js,还是需要再导入上述的bootstrap.js文件,因为它和你之前导入的并不相同。

还有就是即便你已经导入了jquery.min.js,最好还是导入这边的jquery.min.js,因为如果不导入,可能会导致remote类型的验证失效。

2.表单

表单项的填写需要遵从两个原则,表单项的class需标记为:form-control。并且提交按钮的id或者name不要设为sumbit,否则在验证之后会出现无法提交的情况,一个典型的表单如下所示。

    <form id="thisForm" method="post" action="">
<input type="hidden" name="type" value="1" />
<div class="container-fluid ">
<div class="col-xs-12">
<div class="panel-body ">
<div class="box box-danger box-padding">
<div class="row row-margin">
<div class="col-xs-8 col-xs-offset-1 tipinfo">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">合伙人账号</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" name="partnerName">
</div> </div>
</div>
<div class="row row-margin">
<div class="col-xs-8 col-xs-offset-1 tipinfo">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">合伙人手机</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" name="phone">
</div> </div>
</div>
<div class="row row-margin">
<div class="col-xs-8 col-xs-offset-1 tipinfo">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">真实名称</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" name="realName">
</div>
</div>
</div>
<div class="row row-margin">
<div class="col-xs-8 col-xs-offset-1 tipinfo">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">所属级别</button>
</div>
<!-- /btn-group -->
<select class="form-control" name="partnerLevelId">
<option value="1">市级合伙人</option>
<option value="2">生活馆关注</option>
<option value="3">VIP合伙人</option>
</select>
</div>
</div>
</div>
<div class="row row-margin">
<div class="col-xs-8 col-xs-offset-1 tipinfo">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">上级合伙人</button>
</div>
<!-- /btn-group -->
<select name="parentPartnerId" class="form-control">
<OPTION value="0">无</OPTION>
<c:forEach items="${parentPartnerList}" var="parentPartner">
<option value="${parentPartner.partnerId}">${parentPartner.partnerName}</option>
</c:forEach>
</select>
</div>
</div>
</div>
<div class="row row-margin">
<div class="col-xs-8 col-xs-offset-1 tipinfo">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-danger">投资金额</button>
</div>
<!-- /btn-group -->
<input type="text" class="form-control" name="joinFee" placeholder="元">
</div>
</div>
</div>
<div class="row row-margin">
<div class="col-xs-5 col-xs-offset-4">
<button type="button" class="btn btn-default "
onClick="goback();">返回</button>
&nbsp&nbsp
<button type="button" class="btn btn-primary btn-danger"
id="submit1">提交</button>
</div>
</div>
</div> </div>
</div>
</div>
</form>

3.加载验证器

在页面加载完整之后,通过如下js代码加载验证器。

$(function() {
$('#thisForm').formValidation({
message : 'This value is not valid',
icon : {
valid : 'glyphicon glyphicon-ok',
invalid : 'glyphicon glyphicon-remove',
validating : 'glyphicon glyphicon-refresh'
},
fields : {
partnerName : {
message : '合伙人名称验证不通过',
validators : {
notEmpty : {
message : '不能为空'
},
/*
* stringLength: { min: 6, max: 30, message: 'The username must
* be more than 6 and less than 30 characters long' },
*/
/*
* remote: { url: 'remote.php', message: 'The username is not
* available' },
*/
/*
* regexp: { regexp: /^[a-zA-Z0-9_\.]+$/, message: 'The username
* can only consist of alphabetical, number, dot and underscore' }
*/
}
},
realName : {
validators : {
notEmpty : {
message : '不能为空'
},
}
},
phone : {
validators : {
notEmpty : {
message : '不能为空'
},
phone : {
message : '不是有效的电话号码',
country:'CN'
},
remote: {
type: 'POST',
url: 'partnerByPhone',
message: '该号码已经存在',
// delay: 1000
}
}
},
joinFee: {
validators: {
notEmpty: {
message:'不能为空'
},
digits: {
message:'不是有效的金额'
},
greaterThan: {
value: 0
}, }
}
}
})
});

相信很容易就可以看懂上述验证器的逻辑,就是一个封装好的json对象,以表单的name作为键,对每一个表单规定验证规则,以及验证失败后输出的message。以上列出了几种常见的验证规则,如果想要更多验证规则,可以从下载的文件中去找寻demo.

这里再列出一些比较有用的验证规则,都是我从demo上面摘抄下来的。

--长度要求和正则表达式

   username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and can\'t 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, dot and underscore'
}
}
},

--email:

 email: {
validators: {
notEmpty: {
message: 'The email address is required and can\'t be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},

--电话

      phone: {
validators: {
notEmpty: {
message: '不能为空'
},
phone:{
message: '不是合法电话',
country:'CN'
} }
}

--网站

 website: {
validators: {
uri: {
message: 'The input is not a valid URL'
}
}
}

--邮编

  zipCode: {
validators: {
zipCode: {
country: 'CN',//中国邮编
message: 'The input is not a valid US zip code'
}
}
}

--密码及确认

      password: {
validators: {
notEmpty: {
message: 'The password is required and can\'t be empty'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The confirm password is required and can\'t be empty'
},
identical: {
field: 'password',
message: 'The password and its confirm are not the same'
}
}
},

--数字

   age: {
validators: {
notEmpty: {},
digits: {},
greaterThan: {
value: 18
},
lessThan: {
value: 100
}
}
},

 --整数

  'limitPromotion.stock': {
validators: {
notEmpty: {
message:'不能为空'
},
regexp: {
regexp: /^([0-9][0-9]*)$/,
message: '必须为整数'
} }
},

 --日期

'employee.birthday' : {
message : '表单校验失败',
validators : {
notEmpty : {
message : '不能为空'
},
//日期格式
date: {
format: 'YYYY-MM-DD hh:mm:ss',
message : '不是合法的日期'
}
}
},

--远程调用

  username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and can\'t be empty'
},
remote: {
type: 'POST',
url: 'partnerByPhone',
message: '电话号码已使用',
//delay: 1000
}
}
}

关于远程调用就是需要去访问服务端的接口,来验证输入的表单是否有效,经常出现的场景是我们需要验证一个用户名是否已经被注册过了。该远程调用返回的响应是一个json的数据,如果是{ “valid”: true }表示通过验证,否则{ “valid”: false}表示验证失败。

其中服务端的代码示例如下:

    @ResponseBody
@RequestMapping("partnerByPhone")
public Map<String, Object> partnerByPhone(String phone) {
TPartner partner = partnerService.getPartnerByPhone(phone);
Map<String, Object> maps = new HashMap<String, Object>();
if (partner == null) {
maps.put("valid", true);
} else {
maps.put("valid", false);
}
return maps;
}

4.提交表单时候手动调用验证

一般情况下,当我们提交表单的时候,需要手动调用验证,可以用如下代码来实现。针对上述表单。


  $("#submit1").click(function() {
var $form = $("#thisForm");
var bv = $form.data('formValidation');
bv.validate();
if(bv.isValid()){
$.ajax({
type:'post',
url:'partnerSave',
data:$('#thisForm').serialize(),
dataType:'html',
success:function(data){
if(data>0){
alert("成功");
location.href="partnerHome";
}else{
alert("失败");
}
} });
}
});

怎么样,就是这么简单。我们来看看效果吧。当然提示错误的语言和一些标签的样式你可以自己去修改。

表单验证插件--formvalidation

表单验证插件--formvalidation

总的来说,这还是一款比较容易上手的验证器,有需要的朋友可以尝试一下。