表单验证是一个非常基础的功能,当你的表单项少的时候,可以自己写验证,但是当你的表单有很多的时候,就需要一些验证的插件。今天介绍一款很好用的表单验证插件,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的更多相关文章

  1. jquery validate表单验证插件-推荐

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

  2. 表单验证插件之jquery.validate.js

    提到表单验证的插件,第一个想到的就是jquery.validate.js,所以小生想在这里稍微详细地说一下这款插件的具体使用方法,便于理解,我直接附上整段demo的代码(没怎么调样式,主要是看js): ...

  3. jQuery学习之:Validation表单验证插件

    http://polaris.blog.51cto.com/1146394/258781/ 最近由于公司决定使用AJAX + Struts2来重构项目,让我仔细研究一下这两个,然后集中给同事讲讲,让每 ...

  4. jquery validate表单验证插件

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

  5. 表单验证插件 - formValidator

    表单验证插件 - formValidator * 引入formValidator插件文件 * 引入formValidator插件的主文件 * 引入formValidator插件的正则有关文件 * 引入 ...

  6. JS表单验证插件(支持Ajax验证)

    自己编写了一个表单验证插件,支持ajax验证,使用起来很简单. 每个需要验证的表单元素下面有一个span标签,这个标签的class有一个valid表示需要验证,如果有nullable则表示可为空:ru ...

  7. 轻量级实用JQuery表单验证插件:validateForm5

    表单验证是Web项目一个必不可少的环节,而且是一项重复的劳动,于是小菜封装了一款简单的表单验证插件,名字叫:validateForm5. validateForm5插件基于Jquery,并向HTML5 ...

  8. 【jquery】Validform,一款不错的 jquery 表单验证插件

    关于 Validform 这是一款很不错的 jquery 表单验证插件,它几乎能够满足任何验证需求,仅仅一行代码就能搞定整站的表单验证. $('form').Validform(); 为什么能如此方便 ...

  9. 【jQuery基础学习】06 jQuery表单验证插件-Validation

    jQuery的基础部分前面都讲完了,那么就看插件了. 关于jQuery表单验证插件-Validation validation特点: 内置验证规则:拥有必填.数字.E-Mail.URL和信用卡号码等1 ...

随机推荐

  1. 设置Eclipse的workspace路径

    首次启动Eclipse/MyEclipse时, 会弹出"Workspace Launcher"对话框, 提示设置Workspace路径. 设定好路径后, 若勾选了"Use ...

  2. LeetCode OJ 之 Ugly Number II (丑数-二)

    题目: Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime fact ...

  3. python实现斐波那契数列(Fibonacci sequence)

    使用Python实现斐波那契数列(Fibonacci sequence) 斐波那契数列形如 1,1,2,3,5,8,13,等等.也就是说,下一个值是序列中前两个值之和.写一个函数,给定N,返回第N个斐 ...

  4. org.elasticsearch.transport.ReceiveTimeoutTransportException[cluster:monitor/nodes/liveness] request_id [31] timed out after [5000ms]

    ES连接超时,异常信息 2017-09-07 10:42:45.042 [elasticsearch[Bantam][transport_client_worker][T#17]{New I/O wo ...

  5. myeclipse 2014 Customize Perspective 失效

    1.将9个jar复制到myeclipse安装目录\plugins中 2.删除和这9个jar同包名但是版本号较低的9个文件 3.重启myeclipse 2014 注:这9个 jar 包 自己到网上搜索, ...

  6. 解决win7中防火墙的0x6D9问题的方法

    问题: 打开windows防火墙管理单元时出错:代码0x6d9" 解决方法: 下一步-->下一步-->完成.

  7. IOS学习1——IOS应用程序的生命周期及基本架构

    一.应用程序的状态和多任务 有时系统会从app一种状态切换另一种状态来响应系统发生的事件.例如,当用户按下home键.电话打入.或其他中断发生时,当前运行的应用程序会切换状态来响应.应用程序的状态有以 ...

  8. iOS App稳定性指标及监测

    一个App的稳定性,主要决定于整体的系统架构设计,同时也不可忽略编程的细节,正所谓"千里之堤,溃于蚁穴",一旦考虑不周,看似无关紧要的代码片段可能会带来整体软件系统的崩溃.尤其因为 ...

  9. java.util.ConcurrentHashMap (JDK 1.8)

    1.1 java.util.ConcurrentHashMap继承结构 ConcurrentHashMap和HashMap的实现有很大的相似性,建议先看HashMap源码,再来理解Concurrent ...

  10. Oracle数据库部分迁至闪存存储方案

    Oracle数据库部分迁至闪存存储方案 1.实施需求 2.确认迁移表空间信息 3.确认redo信息 4.确认undo信息 5.表空间迁移到闪存 6.redo迁移到闪存 7.undo迁移到闪存 8.备库 ...