首页 > 代码库 > 模仿 BootstrapValidator 自制 模块化 表单验证

模仿 BootstrapValidator 自制 模块化 表单验证

index.html :

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	<title>BootstrapValidator</title>
	<link rel="stylesheet" type="text/css" href="http://www.mamicode.com/assets/bootstrap.min.css">
	<style>
		html,body{
			margin: 0;
			padding: 0;
			width: 100%;
			height: 100%;
		}
		#form-panel{
			width: 40%;
			padding: 30px;
			border: 1px solid #bbb;
			border-radius: 7px;
			margin: auto;
			margin-top: 10%;
		}
		#form-panel .form-control ~ p {
			color: #c7254e;
		}
	</style>
</head>
<body>
	<div id="form-panel">
		<form id="html5Form" method="post" class="form-horizontal">
			<!--
			data-dv-xxxx
			规则1:required=boolean required-message 必填项
			规则2:regex=String regex-message 正则匹配失败
			规则3:email=boolean email-message 邮箱验证失败
			规则4:uri=boolean uri-message 
				age
				greaterthan
				lessthan
			-->
			<div class="form-group">
				<label class="col-lg-3 control-label">Username</label>
				<div class="col-lg-7">
					<input type="text" class="form-control" name="username"
						data-dv-required="true"
						data-dv-required-message="The username is required and cannot be empty"
						data-dv-regex="^[a-zA-Z0-9]+$"
						data-dv-regex-message="The username can only consist of alphabetical,number"
						autocomplete="off" />
				</div>
			</div>

			<div class="form-group">
				<label class="col-lg-3 control-label">Email</label>
				<div class="col-lg-7">
					<input class="form-control" name="email"
						data-dv-required="true"
						data-dv-required-message="The email is required and cannot be empty"
						data-dv-email="true"
						data-dv-email-message="The input is not a valid email address"
						autocomplete="off" />
				</div>
			</div>

			<div class="form-group">
				<label class="col-lg-3 control-label">Website</label>
				<div class="col-lg-7">
					<input class="form-control" name="website"
						data-dv-required="true"
						data-dv-required-message="The website is required and cannot be empty"
						data-dv-uri="true"
						data-dv-uri-message="The input is not a valid website address"
						autocomplete="off" />
				</div>
			</div>

			<div class="form-group">
				<label class="col-lg-3 control-label">Age</label>
				<div class="col-lg-7">
					<input type="text" class="form-control" name="age"
						data-dv-required="true"
						data-dv-required-message="The age is required and cannot be empty"
						data-dv-greaterthan="10"
						data-dv-greaterthan-message="The input must be greater than or equal to 10"
						data-dv-lessthan="100"
						data-dv-lessthan-message="The input must be less than 100"
						data-dv-integer="true"
						data-dv-integer-message="The input must be integer"
						autocomplete="off" />
				</div>
			</div>

			<div class="form-group">
				<div class="col-lg-12 text-center">
					<input class="btn btn-primary" type="button" value="http://www.mamicode.com/Regist" />
					<input class="btn btn-primary" type="reset" value="http://www.mamicode.com/Reset" />
				</div>
			</div>	
		</form>
	</div>

	<script src="http://www.mamicode.com/assets/jquery.min.js"></script></body>
	<script src="http://www.mamicode.com/bootstrap-dn-validator-1.11.0/js/bootstrap-dn-validator.js"></script>
	<script>
		// 1.json数据格式
		// $(document).ready(function() {
		// 	$(‘#html5Form‘).dnValidator({
		// 		"username":"/^$/",
		// 		"age":"/^$/"
		// 	});
		// });

		$(document).ready(function() {
			$(‘#html5Form‘).dnValidator({
				trigger:"keyup"
			});
		});
	</script>
</html>

 

bootstrap-dn-validator.js :

// bootstrap自定义插件有两种方式来实现参数配置
// 1.json数据格式
// 2.html attribute(属性)配置

// 1.创建闭包
(function(root,factory,plug){
	// 4.创建闭包对象
	return factory(root.jQuery,plug);
})(window,function($,plug){ // 3.传入 $ plug
	// 9.默认参数 保证健壮性
	var __DEFS__ = {
		trigger:"change"
	};

	// 11.规则引擎
	var __RULES__ = {
		required:function(){
			// console.log(‘required‘ + this.val());
			return this.val()!=="";
		},
		regex:function(){
			return new RegExp(this.data("dv-regex")).test(this.val());
		},
		email:function(){
			return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(this.val());
		},
		uri:function(){
			return /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?$/.test(this.val());
		},
		// 扩展
		integer:function(){
			return /^[0-9]*[1-9][0-9]*$/.test(this.val());
		},
		greaterthan:function(){
			return Number(this.val())>Number(this.data("dv-greaterthan"));
		},
		lessthan:function(){
			return Number(this.val())<Number(this.data("dv-lessthan"));
		}
	}

	// 5.进行插件扩展 可以对jQuery进行重命名(通过创建作用,命令别名)
	// 创建dnValidator插件
	$.fn[plug] = function(options){ // 8.options 用户传参
		// 10.继承
		$.extend(this,__DEFS__,options);
		// 6.找到表单中所有的input标签
		var $fileds = this.find("input").not("[type=button],[type=reset],[type=submit]"); // 需要验证的表单域
		// console.log($fileds.size()); // input个数
		// 7.绑定事件
		$fileds.on(this.trigger,function(){
			var $field = $(this); // 被验证的目标对象
			var result = true; // 14.验证结果,默认通过
			$field.next().remove(); // 17.验证之前先把之前的错误信息移除掉
			// 12.迭代rule
			$.each(__RULES__,function(rule,valider){ // rule规则  valider验证器
				// 13.判断目标对象被哪些规则验证
				if($field.data("dv-"+rule)){
					// 我需要验证rule这个规则
					// console.log($field.attr("name") + "需要验证" + rule + "规则");
					// 15.判断,只要有一个验证失败,就停止验证
					result = valider.call($field); // true false call改变作用域
					if(!result){ // 验证失败
						// 16.显示提示信息
						$field.after("<p>" + $field.data("dv-" + rule + "-message") + "</p>");
					}
					return result;
				}
			});
		});
	}
},"dnValidator")
// 2.匿名函数调用
// 参数1:window对象
// 参数2:function(){} 回调函数
// 参数3:插件名称

 

.

模仿 BootstrapValidator 自制 模块化 表单验证