GVKun编程网logo

jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法

10

以上就是给各位分享jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法,同时本文还将给你拓展bootstrap+bootstrap-table+jquery+

以上就是给各位分享jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法,同时本文还将给你拓展bootstrap + bootstrap-table + jquery + bootstrap-paginator、bootstrap bootstrapvalidator插件+adjax验证使用、Bootstrap Validator 表单验证、Bootstrap Validator表单验证插件等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法

jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法

使用bootstrap遇到表单校验,最常用的一款表单校验插件

github地址:https://github.com/nghuuphuoc/bootstrapvalidator 

使用:

将文件下载 或者用 git clone下来

分享图片

1.引入css到head中,引入js到body结束标签的前面即可

 

提示:

分享图片

默认是英语的,需要变成中文:

将github中dist中的\js\language\zh_CN.js 引入文件中即可

官方完整实例版:

<!DOCTYPE html>
<html>
<head>
<title>BootstrapValidator demo</title>
<link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" href="dist/css/bootstrapValidator.css"/>
<!-- Include the FontAwesome CSS if you want to use Feedback icons provided by FontAwesome -->
<!--<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/../css/font-awesome.css" />-->
<script type="text/javascript" src="vendor/jquery/jquery-...min.js"></script>
<script type="text/javascript" src="vendor/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="dist/js/bootstrapValidator.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<!-- form: -->
<section>
<div class="col-lg- col-lg-offset-">
<div class="page-header">
<h>Sign up</h>
</div>
<form id="defaultForm" method="post" class="form-horizontal" action="target.PHP">
<div class="form-group">
<label class="col-lg- control-label">Full name</label>
<div class="col-lg-">
<input type="text" class="form-control" name="firstName" placeholder="First name" />
</div>
<div class="col-lg-">
<input type="text" class="form-control" name="lastName" placeholder="Last name" />
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Username</label>
<div class="col-lg-">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Email address</label>
<div class="col-lg-">
<input type="text" class="form-control" name="email" />
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Password</label>
<div class="col-lg-">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Retype password</label>
<div class="col-lg-">
<input type="password" class="form-control" name="confirmPassword" />
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Gender</label>
<div class="col-lg-">
<div class="radio">
<label>
<input type="radio" name="gender" value="male" /> Male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="female" /> Female
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="other" /> Other
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Birthday</label>
<div class="col-lg-">
<input type="text" class="form-control" name="birthday" /> (YYYY/MM/DD)
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Languages</label>
<div class="col-lg-">
<div class="checkBox">
<label>
<input type="checkBox" name="languages[]" value="english" /> English
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="languages[]" value="french" /> french
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="languages[]" value="german" /> German
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="languages[]" value="russian" /> Russian
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="languages[]" value="other" /> Other
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg- control-label">Programming Languages</label>
<div class="col-lg-">
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="net" /> .Net
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="java" /> Java
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="c" /> C/C++
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="PHP" /> PHP
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="perl" /> Perl
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="ruby" /> Ruby
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="python" /> Python
</label>
</div>
<div class="checkBox">
<label>
<input type="checkBox" name="programs[]" value="javascript" /> Javascript
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label" id="captchaOperation"></label>
<div class="col-lg-2">
<input type="text" class="form-control" name="captcha" />
</div>
</div>
<div class="form-group">
<div class="col-lg-9 col-lg-offset-3">
<button type="submit" class="btn btn-primary" name="signup" value="Sign up">Sign up</button>
<button type="submit" class="btn btn-primary" name="signup2" value="Sign up 2">Sign up 2</button>
<button type="button" class="btn btn-info" id="validateBtn">Manual validate</button>
<button type="button" class="btn btn-info" id="resetBtn">Reset form</button>
</div>
</div>
</form>
</div>
</section>
<!-- :form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
// Generate a simple captcha
function randomNumber(min,max) {
return Math.floor(Math.random() * (max - min + 1) + min);
};
$(#captchaOperation).html([randomNumber(1,100),+,randomNumber(1,200),=].join( ));
$(#defaultForm).bootstrapValidator({
// live: ‘disabled‘,
message: This value is not valid,FeedbackIcons: {
valid: glyphicon glyphicon-ok,invalid: glyphicon glyphicon-remove,validating: glyphicon glyphicon-refresh
},fields: {
firstName: {
validators: {
notEmpty: {
message: The first name is required and cannot be empty
}
}
},lastName: {
validators: {
notEmpty: {
message: The last name is required and cannot be empty
}
}
},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,dot and underscore
},remote: {
url: remote.PHP,message: The username is not available
},different: {
field: password,message: The username and password cannot be the same as each other
}
}
},email: {
validators: {
emailAddress: {
message: The input is not a valid email address
}
}
},password: {
validators: {
notEmpty: {
message: The password is required and cannot be empty
},identical: {
field: confirmPassword,message: The password and its confirm are not the same
},different: {
field: username,message: The password cannot be the same as username
}
}
},confirmPassword: {
validators: {
notEmpty: {
message: The confirm password is required and cannot be empty
},identical: {
field: password,birthday: {
validators: {
date: {
format: YYYY/MM/DD,message: The birthday is not valid
}
}
},gender: {
validators: {
notEmpty: {
message: The gender is required
}
}
},languages[]: {
validators: {
notEmpty: {
message: Please specify at least one language you can speak
}
}
},programs[]: {
validators: {
choice: {
min: 2,max: 4,message: Please choose 2 - 4 programming languages you are good at
}
}
},captcha: {
validators: {
callback: {
message: Wrong answer,callback: function(value,validator) {
var items = $(#captchaOperation).html().split( ),sum = parseInt(items[]) + parseInt(items[]);
return value == sum;
}
}
}
}
}
});
// Validate the form manually
$(#validateBtn).click(function() {
$(#defaultForm).bootstrapValidator(validate);
});
$(#resetBtn).click(function() {
$(#defaultForm).data(bootstrapValidator).resetForm(true);
});
});
</script>
</body>
</html>

触发校验用:

$(‘表单元素form‘).bootstrapValidator(‘validate‘);

常见问题:

1.插件自带的一个功能,点击校验按钮,校验失败按钮被禁止,校验成功才解开禁止

2.提交按钮不在form表单中,通过事件绑定进行ajax数据提交,当表单验证失败时不执行所绑定的后续事件,怎么解决? 

解决方案如下:

$("表单").submit(function(ev){ev.preventDefault();});
$(
"表单外的按钮元素").on("click",function(){
// 触发校验获取校验结果
var bootstrapValidator = $("表单").data(‘bootstrapValidator‘); bootstrapValidator.validate();

// 判断是否校验成功
if(bootstrapValidator.isValid())
// 校验成功调用submit触发表单提交 $(
"你的表单元素").submit();
//如果校验不成功就直接返回,不触发按钮
else return; });

bootstrap + bootstrap-table + jquery + bootstrap-paginator

bootstrap + bootstrap-table + jquery + bootstrap-paginator

 

http://127.0.0.1:8848/pangBo/index.html

 

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
		 crossorigin="anonymous">
		<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
		 crossorigin="anonymous"></script>
		<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.css">
		<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
		<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/locale/bootstrap-table-zh-CN.min.js"></script>
		<script src="js/bootstrap-paginator.min.js" type="text/javascript" charset="utf-8"></script>
	</head>

	<body>
		<div>
			<formrole="search">
				<div>
					<div>
						<div>
							<label>客户编号: </label>
							<div>
								<input type="text"placeholder="">
							</div>
						</div>
						<div>
							<label>客户姓名: </label>
							<div>
								<input type="text"placeholder="">
							</div>
						</div>
						<div>
							<label>手机号码: </label>
							<div>
								<input type="text"placeholder="">
							</div>
						</div>
					</div>
					<div>
						<div>
							<label>客户编号: </label>
							<div>
								<input type="text"placeholder="">
							</div>
						</div>
						<div>
							<label>客户编号: </label>
							<div>
								<input type="text"placeholder="">
							</div>
						</div>
						<div>
							<label>客户编号: </label>
							<div>
								<input type="text"placeholder="">
							</div>
						</div>
					</div>
					<div>
						<button type="submit">查询</button>
					</div>
				</div>
			</form>
		</div>
		<div>
			<divrole="group" aria-label="...">
				<button type="button" id="btn-one">可撤单</button>
				<button type="button" id="btn-two">已撤单</button>
			</div>
		</div>
		<div id="table-one">
			<table id="table"></table>
			<div>
				<div id="example">
					<ul id="pageLimit"></ul>
				</div>
			</div>
		</div>
		<div id="table-two">
			<table id="table-ta-one"></table>
			<div>
				<div id="example-two">
					<ul id="pageLimit-two"></ul>
				</div>
			</div>
		</div>
		<divid="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
			<div>
				<div>
					<div>
						<button type="button"data-dismiss="modal" aria-hidden="true">&times;</button>
						<divid="myModalLabel">请输入登录密码:</div>
					</div>
					<div>
						<div>
							<input id="input-text" type="text" value=""placeholder="">
						</div>
						<button type="button" id="btn-ok">确定撤单</button>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>
<script type="text/javascript">
	function operateFormatter(value, row, index) {
		return [
			''<button type="button"data-toggle="modal" data-target="#myModal">撤单</button>''
		].join('''');
	}
	window.operateEvents = {
		''click .RoleOfdelete'': function(e, value, row, index) {
			console.log(''kkk'');
		}
	};
	$(''#table'').bootstrapTable({
		url: '''', //请求后台的URL(*)
		method: ''GET'', //请求方式(*)
		// toolbar: ''#toolbar'', //工具按钮用哪个容器
		cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
		pagination: false, //是否显示分页(*)
		// pageSize: 10, //每页的记录行数(*)
		// pageNumber: 1, //初始化加载第一页,默认第一页,并记录
		// sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
		uniqueId: "id", //每一行的唯一标识,一般为主键列
		columns: [{
				field: ''id'',
				align: ''center'',
				title: ''交易合同号''
			},
			{
				field: ''ida'',
				align: ''center'',
				title: ''客户编号''
			},
			{
				field: ''idb'',
				align: ''center'',
				title: ''客户姓名''
			},
			{
				field: ''idc'',
				align: ''center'',
				title: ''手机号码''
			},
			{
				field: ''idd'',
				align: ''center'',
				title: ''证件号码''
			},
			{
				field: ''ide'',
				align: ''center'',
				title: ''产品代码''
			},
			{
				field: ''idf'',
				align: ''center'',
				title: ''产品名称''
			},
			{
				field: ''idg'',
				align: ''center'',
				title: ''购买金额''
			},
			{
				field: ''idh'',
				align: ''center'',
				title: ''交易时间''
			},
			{
				field: ''idi'',
				align: ''center'',
				title: ''撤单'',
				events: operateEvents,
				formatter: operateFormatter
			},
		],
		data: [{
				id: 1
			},
			{
				id: 1
			},
			{
				id: 1
			}
		],
		onLoadError: function() {
			showTips("数据加载失败!");
		},

	});
	$(''#table-ta-one'').bootstrapTable({
		url: '''', //请求后台的URL(*)
		method: ''GET'', //请求方式(*)
		// toolbar: ''#toolbar'', //工具按钮用哪个容器
		cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
		pagination: false, //是否显示分页(*)
		// pageSize: 10, //每页的记录行数(*)
		// pageNumber: 1, //初始化加载第一页,默认第一页,并记录
		// sidePagination: "server", //分页方式:client客户端分页,server服务端分页(*)
		uniqueId: "id", //每一行的唯一标识,一般为主键列
		columns: [{
				field: ''id'',
				align: ''center'',
				title: ''交易合同号''
			},
			{
				field: ''ida'',
				align: ''center'',
				title: ''客户编号''
			},
			{
				field: ''idb'',
				align: ''center'',
				title: ''客户姓名''
			},
			{
				field: ''idc'',
				align: ''center'',
				title: ''手机号码''
			},
			{
				field: ''idd'',
				align: ''center'',
				title: ''证件号码''
			},
			{
				field: ''ide'',
				align: ''center'',
				title: ''产品代码''
			},
			{
				field: ''idf'',
				align: ''center'',
				title: ''产品名称''
			},
			{
				field: ''idg'',
				align: ''center'',
				title: ''购买金额''
			},
			{
				field: ''idh'',
				align: ''center'',
				title: ''交易时间''
			}
		],
		data: [{
				id: 1
			},
			{
				id: 1
			},
			{
				id: 1
			}
		],
		onLoadError: function() {
			showTips("数据加载失败!");
		},

	});
	$(''#btn-one'').click(function() {
		console.log(''kk'');
		$(''#table-one'').show();
		$(''#table-two'').hide();
		$(''#btn-one'').css({
			''background-color'': ''#e6e6e6''
		})
	})
	$(''#btn-two'').click(function() {
		console.log(''kkk'');
		$(''#table-two'').show();
		$(''#table-one'').hide();
		$(''#btn-one'').css({
			''background-color'': ''#FFF''
		})
	})
	$(''#pageLimit'').bootstrapPaginator({
		currentPage: 1, //当前的请求页面。
		totalPages: 100, //一共多少页。
		size: "normal", //应该是页眉的大小。
		bootstrapMajorVersion: 3, //bootstrap的版本要求。
		alignment: "right",
		numberOfPages: 5, //一页列出多少数据。
		itemTexts: function(type, page, current) { //如下的代码是将页眉显示的中文显示我们自定义的中文。
			switch (type) {
				case "first":
					return "首页";
				case "prev":
					return "上一页";
				case "next":
					return "下一页";
				case "last":
					return "末页";
				case "page":
					return page;
			}
		}
	});
	$(''#pageLimit-two'').bootstrapPaginator({
		currentPage: 1, //当前的请求页面。
		totalPages: 100, //一共多少页。
		size: "normal", //应该是页眉的大小。
		bootstrapMajorVersion: 3, //bootstrap的版本要求。
		alignment: "right",
		numberOfPages: 5, //一页列出多少数据。
		itemTexts: function(type, page, current) { //如下的代码是将页眉显示的中文显示我们自定义的中文。
			switch (type) {
				case "first":
					return "首页";
				case "prev":
					return "上一页";
				case "next":
					return "下一页";
				case "last":
					return "末页";
				case "page":
					return page;
			}
		}
	});
	$(''#btn-ok'').click(function() {
		var inputContent = $(''#input-text'').val();
		if (inputContent == '''') {
			alert(''密码不能为空 !'');
		}
		console.log(inputContent);
	})
</script>

 

bootstrap bootstrapvalidator插件+adjax验证使用

bootstrap bootstrapvalidator插件+adjax验证使用

1、利用bootstrap Validator表单验证进行表单验证需要如下CSS和JS.

<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />

<link rel="stylesheet" type="text/css" href="css/bootstrapValidator.css" />

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

具体样式找bootstrap Validator官网

 

2、validate规则配置

<script type="text/javascript">
$(function () {
$(''form'').bootstrapValidator({
message: ''This value is not valid'',
feedbackIcons: {
valid: ''glyphicon glyphicon-ok'',
invalid: ''glyphicon glyphicon-remove'',
validating: ''glyphicon glyphicon-refresh''
},
fields: {
account: {
message: ''用户名验证失败'',
validators: {
stringLength: {
min: 3,
max: 15,
message: ''用户名长度必须在3到15位之间''
},
regexp: {
regexp: /^[a-z0-9_-]{3,16}$/,
message: ''用户名只能包含、小写、数字和下划线''
}
}
},
password: {
validators: {
stringLength: {
min: 6,
max: 18,
message: ''密码长度必须在6到18位之间''
},
regexp: {
regexp: /^[a-z0-9_-]{3,16}$/,
message: ''密码只能包含、小写、数字和下划线''
}
}
},
repassword: {
message: ''密码无效'',
validators: {
identical: {//相同
field: ''password'',
message: ''两次密码不一致''
},
}
},
email: {
validators: {
emailAddress: {
message: ''邮箱地址格式有误''
}
}
}
}
});
});

 


3、对应的html页面如下

<div>
<h3>GET STARTED</h3>
<formrole="form" id="register_form">
<div>
<inputname="account" id="account" type="text"
placeholder="Your Account">
</div>
<div>
<inputname="email" id="email" type="text"
placeholder="Your Email">
</div>
<div>
<inputname="password" id="password" type="password"
placeholder="Password">
</div>
<div>
<inputname="repassword" id="repassword" type="password"
placeholder="Repassword">
</div>
<div>
<input type="button"value="Register"
onclick="register_ajax(''#register_form'')">
</div>
<p>Do have account? Please <a
href="/api/login/">Login</a>.</p>
</form>
</div>

 

4、ajax 处理表单提交脚本如下:

 

/*表单信息异步传输*/
function register_ajax(id) {
if ($(id).data(''bootstrapValidator'').isValid()) {
var data = $(id).serializeJSON();
var url;
if (id === "#register_form") {
url = ''/api/register/'';
}
$.ajax({
type: ''post'',
url: url,
data: JSON.stringify(data),
contentType: "application/json",
success: function (data) {
if (data === ''恭喜您,账号已成功注册'') {
window.location.href = ''/api/login/'';
} else {
alert(data);
}
},
error: function () {
alert(''Sorry,服务器可能开小差啦, 请重试!'')
}
});
}
}

 

其他的一些用法可以参考https://www.cnblogs.com/zhangtongzct/p/5728592.html

Bootstrap Validator 表单验证

Bootstrap Validator 表单验证

在线演示地址:

使用方法,代码如下所示:

rush:js;"> 1.
PHP"> 2. 用户名 4. 6.
7.
8. 9. 11. 13.
14.
15. 16. 18. (YYYY/MM/DD) 20. 21. 22. 23. 26. 27. 29. 30. 1.$('#defaultForm').bootstrapValidator({ 2. message: 'This value is not valid',3. FeedbackIcons: { 4. valid: 'glyphicon glyphicon-ok',5. invalid: 'glyphicon glyphicon-remove',6. validating: 'glyphicon glyphicon-refresh' 7. },8. fields: { 9. username: { 10. message: 'The username is not valid',11. validators: { 12. notEmpty: { 13. message: 'The username is required and cannot be empty' 14. },15. stringLength: { 16. min: 6,17. max: 30,18. message: 'The username must be more than 6 and less than 30 characters long' 19. },20. regexp: { 21. regexp: /^[a-zA-Z0-9_\.]+$/,22. message: 'The username can only consist of alphabetical,number,dot and underscore' 23. },24. remote: { 25. url: 'remote.PHP',26. message: 'The username is not available' 27. },28. different: { 29. field: 'password',30. message: 'The username and password cannot be the same as each other' 31. } 32. } 33. },34. email: { 35. validators: { 36. emailAddress: { 37. message: 'The input is not a valid email address' 38. } 39. } 40. },41. } 42.});

Bootstrap Validator表单验证插件

Bootstrap Validator表单验证插件

引入必要文件

<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet">
...
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.bootcss.com/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js"></script>

HTML编写

<form id="defaultForm" method="post"action="target.php">
    <div>
        <label>Full name</label>
        <div>
            <input type="text"name="firstName" placeholder="First name" />
        </div>
        <div>
            <input type="text"name="lastName" placeholder="Last name" />
        </div>
    </div>

    <div>
        <label>Username</label>
        <div>
            <input type="text"name="username" />
        </div>
    </div>

    <div>
        <label>Email address</label>
        <div>
            <input type="text"name="email" />
        </div>
    </div>

    <div>
        <label>Password</label>
        <div>
            <input type="password"name="password" />
        </div>
    </div>

    <div>
        <label>Retype password</label>
        <div>
            <input type="password"name="confirmPassword" />
        </div>
    </div>

    <div>
        <label>Gender</label>
        <div>
            <div>
                <label>
                    <input type="radio" name="gender" value="male" /> Male
                </label>
            </div>
            <div>
                <label>
                    <input type="radio" name="gender" value="female" /> Female
                </label>
            </div>
            <div>
                <label>
                    <input type="radio" name="gender" value="other" /> Other
                </label>
            </div>
        </div>
    </div>

    <div>
        <label>Birthday</label>
        <div>
            <input type="text"name="birthday" /> (YYYY/MM/DD)
        </div>
    </div>

    <div>
        <label>Languages</label>
        <div>
            <div>
                <label>
                    <input type="checkbox" name="languages[]" value="english" /> English
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="languages[]" value="french" /> French
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="languages[]" value="german" /> German
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="languages[]" value="russian" /> Russian
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="languages[]" value="other" /> Other
                </label>
            </div>
        </div>
    </div>

    <div>
        <label>Programming Languages</label>
        <div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="net" /> .Net
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="java" /> Java
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="c" /> C/C++
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="php" /> PHP
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="perl" /> Perl
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="ruby" /> Ruby
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="python" /> Python
                </label>
            </div>
            <div>
                <label>
                    <input type="checkbox" name="programs[]" value="javascript" /> Javascript
                </label>
            </div>
        </div>
    </div>

    <div>
        <labelid="captchaOperation"></label>
        <div>
            <input type="text"name="captcha" />
        </div>
    </div>

    <div>
        <div>
            <button type="submit"name="signup" value="Sign up">Sign up</button>
            <button type="submit"name="signup2" value="Sign up 2">Sign up 2</button>
            <button type="button"id="validateBtn">Manual validate</button>
            <button type="button"id="resetBtn">Reset form</button>
        </div>
    </div>
</form>

JS编写

<script type="text/javascript">
    $(document).ready(function() {
        function randomNumber(min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min);
        };
        $(''#captchaOperation'').html([randomNumber(1, 100), ''+'', randomNumber(1, 200), ''=''].join('' ''));

        // 验证表单的规则
        $(''#defaultForm'').bootstrapValidator({
            live: ''enabled'',
            message: ''输入的值无效'',
            feedbackIcons: {
                valid: ''glyphicon glyphicon-ok'',
                invalid: ''glyphicon glyphicon-remove'',
                validating: ''glyphicon glyphicon-refresh''
            },
            fields: {
                firstName: {
                    group: ''.col-lg-4'',
                    validators: {
                        notEmpty: {
                            message: ''不能为空''
                        }
                    }
                },
                lastName: {
                    group: ''.col-lg-4'',
                    validators: {
                        notEmpty: {
                            message: ''不能为空''
                        }
                    }
                },
                username: {
                    message: ''用户名无效'',
                    validators: {
                        notEmpty: {
                            message: ''请输入用户名''
                        },
                        stringLength: {
                            min: 6,
                            max: 30,
                            message: ''用户名长度在 6-30 个字符之间''
                        },
                        regexp: {
                            regexp: /^[a-zA-Z0-9_\.]+$/,
                            message: ''用户名包含特殊字符''
                        },
                        remote: {
                            type: ''POST'',
                            url: ''remote.php'',
                            message: ''用户名不可用''
                        },
                        different: {
                            field: ''password, confirmPassword'',
                            message: ''用户名和密码不能相同''
                        }
                    }
                },
                email: {
                    validators: {
                        emailAddress: {
                            message: ''请输入正确的邮箱格式''
                        }
                    }
                },
                password: {
                    validators: {
                        notEmpty: {
                            message: ''请输入密码''
                        },
                        identical: {
                            field: ''confirmPassword'',
                            message: ''两次密码必须输入一致''
                        },
                        different: {
                            field: ''username'',
                            message: ''用户名和密码不能相同''
                        }
                    }
                },
                confirmPassword: {
                    validators: {
                        notEmpty: {
                            message: ''请确认密码''
                        },
                        identical: {
                            field: ''password'',
                            message: ''两次密码必须输入一致''
                        },
                        different: {
                            field: ''username'',
                            message: ''用户名和密码不能相同''
                        }
                    }
                },
                birthday: {
                    validators: {
                        date: {
                            format: ''YYYY/MM/DD'',
                            message: ''请输入正确的邮箱格式''
                        }
                    }
                },
                gender: {
                    validators: {
                        notEmpty: {
                            message: ''请选择一个性别''
                        }
                    }
                },
                ''languages[]'': {
                    validators: {
                        notEmpty: {
                            message: ''至少选择一个语言''
                        }
                    }
                },
                ''programs[]'': {
                    validators: {
                        choice: {
                            min: 2,
                            max: 4,
                            message: ''请选择 2-4 个编程语言''
                        }
                    }
                },
                captcha: {
                    validators: {
                        callback: {
                            message: ''错误的答案'',
                            callback: function(value, validator) {
                                var items = $(''#captchaOperation'').html().split('' ''), sum = parseInt(items[0]) + parseInt(items[2]);
                                return value == sum;
                            }
                        }
                    }
                }
            }
        }).on(''success.form.bv'', function(e) {
            // 设定默认提交方式,防止重复提交
            e.preventDefault();

            // 提交表单逻辑
            // $.ajax( ... );
        });

        // 验证表单
        $(''#validateBtn'').click(function() {
            $(''#defaultForm'').bootstrapValidator(''validate'');
            $("#modal_form").data("bootstrapValidator").isValid(); // 验证表单状态,成功返回true失败返回false
        });

        // 重置表单验证
        $(''#resetBtn'').click(function() {
            $(''#defaultForm'').data(''bootstrapValidator'').resetForm(true);
        });
    });
</script>

今天关于jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法的讲解已经结束,谢谢您的阅读,如果想了解更多关于bootstrap + bootstrap-table + jquery + bootstrap-paginator、bootstrap bootstrapvalidator插件+adjax验证使用、Bootstrap Validator 表单验证、Bootstrap Validator表单验证插件的相关知识,请在本站搜索。

本文标签: