前端简单入门第二十二讲 使用jQuery完成表单校验

还记得我之前写过的前端简单入门第十一讲 使用JavaScript完成注册页面表单提示及校验一文吗?之前我是使用JavaScript完成了表单的简单校验,即在用户提交表单的时候,我们最好是能够在用户数据提交给服务器之前去做一次校验,防止服务器压力过大,并且需要给用户一个友好提示。
在本文中,我会使用jQuery完成表单的简单校验,不可避免地要知道jQuery中两个常用的事件处理函数,它们是trigger和triggerHandler。

trigger和triggerHandler

查看jQuery API帮助文档可知:

  • trigger:在每一个匹配的元素上触发某类事件。这个函数也会导致浏览器同名的默认行为的执行。比如,如果用trigger()触发一个’submit’,则同样会导致浏览器提交表单。如果要阻止这种默认行为,应返回false;
  • triggerHandler:这个特别的方法将会触发指定的事件类型上所有绑定的处理函数。但不会执行浏览器默认动作,也不会产生事件冒泡。

下面通过一个示例让初学者更加清晰直观地了解这两个事件处理函数。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<!--
			trigger:触发
		-->
		<script type="text/javascript" src="../js/jquery-1.11.0.js" ></script>
		<script>
			$(function() {
				$("#username").focus(function() {
					console.log("text foucs事件被触发了");
				});
				
				$("#btn1").click(function() {
					//触发一下文本框的focus事件
					$("#username").trigger("focus");
				});
				
				$("#btn2").click(function() {
					//触发一下文本框的focus事件
					$("#username").triggerHandler("focus");
				});
			});
		</script>
	</head>
	<body>
		<input type="text" id="username" />
		<input type="button" value="trigger(触发)一下文本框的focus事件" id="btn1" />
		<input type="button" value="triggerHandler(触发)一下文本框的focus事件" id="btn2" />
	</body>
</html>

在Chrome浏览器上的运行效果如下。
前端简单入门第二十二讲 使用jQuery完成表单校验
这里验证了trigger()不仅触发了文本框的focus事件,还执行了类似浏览器将光标移到输入框内的这种浏览器默认行为;triggerHandler()仅仅只触发了focus事件所对应的函数。

使用jQuery完成表单校验

为了给用户一个样式友好的提示,我提前准备好了一个样式层叠表——style.css,其内容如下:

body { font:12px/19px Arial, Helvetica, sans-serif; color:#666;}
form div { margin:5px 0;}
.int label { float:left; width:100px; text-align:right;}
.int input { padding:1px 1px; border:1px solid #ccc;height:16px;}
.sub { padding-left:100px;}
.sub input { margin-right:10px; }
.formtips{width: 200px;margin:2px;padding:2px;}
.onError{
    background:#FFE0E9 url(../img/reg3.gif) no-repeat 0 center;
	padding-left:25px;
}
.onSuccess{
    background:#E9FBEB url(../img/reg4.gif) no-repeat 0 center;
	padding-left:25px;
}
.high{
    color:red;
}

/*
  div,span,p {
    width:140px;
    height:140px;
    margin:5px;
    background:#aaa;
	border:#000 1px solid;
    float:left;
    font-size:17px;
    font-family:Verdana;
  }
  div.mini { 
    width:55px;
    height:55px;
    background-color: #aaa;
    font-size:12px;
  }
  div.hide { 
    display:none;
  }
*/

table		{ border:0;border-collapse:collapse;}
td	{ font:normal 12px/17px Arial;padding:2px;width:100px;}
th			{ font:bold 12px/17px Arial;text-align:left;padding:4px;border-bottom:1px solid #333;}
.even		{ background:#FFF38F;}  /* 偶数行样式*/
.odd		{ background:#FFFFEE;}  /* 奇数行样式*/
.selected		{ background:#FF6500;color:#fff;}

读者要做的事就是导入样式层叠表——style.css。首先我从自己编写的注册页面中抽出核心代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<link rel="stylesheet" href="../css/style.css" />
		<script type="text/javascript" src="../js/jquery-1.11.0.js" ></script>
	</head>
	<body>
		<form action="../index.html">
			<div>
				用户名:<input type="text" class="bitian" id="username" />
			</div>
			<div>
				密码:<input type="password" class="bitian" id="password" />
			</div>
			<div>
				手机号:<input type="tel" />
			</div>
			<div>
				<input type="submit" />
			</div>
		</form>
	</body>
</html>

接着就要编写jQuery代码完成注册页面表单的简单校验了。

<script>
$(function() {//文档加载完成事件要默认做一些页面初始化
	//动态地在必填项后面添加一个小红点
	$(".bitian").after("<font class='high'>*</font>");
	
	//给输入必填项绑定事件
	$(".bitian").blur(function() {
		//首先获取用户当前输入的值
		var value = this.value;
		
		//清空上一次提示的信息
		$(this).parent().find(".formtips").remove();
		
		//判断当前的值是哪一项文本框输入的值
		if($(this).is("#username")) {//判断是否是用户名输入项
			if(value.length < 6) {
				$(this).parent().append("<span class='formtips onError'>用户名太短了</span>");
			} else {
				$(this).parent().append("<span class='formtips onSuccess'>用户名够用</span>");
			}
		}
		
		if($(this).is("#password")) {//判断是否是用户名输入项
			if(value.length < 6) {
				$(this).parent().append("<span class='formtips onError'>密码太短了</span>");
			} else {
				$(this).parent().append("<span class='formtips onSuccess'>密码够用</span>");
			}
		}
	}).focus(function() {
		$(this).triggerHandler("blur");
	}).keyup(function() {
		$(this).triggerHandler("blur");
	});
	
	//给表单提交绑定事件
	$("form").submit(function() {
		//触发所有必填项的校验
		$(".bitian").trigger("focus");
		//找到错误提示信息的个数
		if ($(".onError").length > 0) {
			return false;
		}
		return true;
	});
});
</script>

注意,jQuery中可以这样链式调用:

$(".bitian").blur(function () {}).focus(function() {}).keyup(function() {});//链式调用

这样,在Chrome浏览器上运行,效果如下:
前端简单入门第二十二讲 使用jQuery完成表单校验