DOM(三)-10-(示例-表单校验-涉及的正则校验)

<!--
表单校验:涉及的正则校验
-->

<html>
	<head>
		<style type="text/css">
		</style>
	</head>
	<body>
		<script type="text/javascript">
		
			//发现很多框的校验出了几个内容不同外,校验过程是一样的
			/*
			 *所以进行了代码的提取,其中name代表“用户名称”一栏的name="user"属性;
			 *reg代表正则表达式,即用于校验的标准;spanId是span区域的id号;
			 *okinfo是校验正确的提示信息;errinfo是校验错误的提示信息。
			 *
			 *
			 *
			 */
			function check(name,reg,spanId,okinfo,errinfo){
				
				var flag;
				var val = document.getElementsByName(name)[0].value;
				var oSpanNode = document.getElementById(spanId);
				if(reg.test(val)){
					
					oSpanNode.innerHTML = okinfo.fontcolor("blue");
					flag = true;
				}else{
					
					oSpanNode.innerHTML = errinfo.fontcolor("red");
					flag = false;
				}
			}
			
			//校验用户名
			function checkUser(){
				
				var reg = new RegExp("^[a-z]{4}$","i");
				check("user",reg,"userspan","用户名正确","用户名错误");
			}
			
			//校验密码
			function checkPsw(){
				
				var reg = new RegExp("^[0-9]{4}$");
				check("psw",reg,"pswspan","密码格式正确","密码格式错误");
			}
			
			//校验确认密码:只要和密码一致即可
			function checkRePsw(){
				
				var flag;
				//获取密码框内容
				var pass = document.getElementsByName("psw")[0].value;
				
				//获取确认密码框内容
				var repass = document.getElementsByName("repsw")[0].value;
				
				//获取确认密码的span区域
				var oRePassSpanNode = document.getElementById("repswspan");
				
				//判断两次密码是否相同
				if(pass == repass){
					
					oRePassSpanNode.innerHTML = "两次输入密码一致".fontcolor("blue");
					flag = true;
				}else{
					
					oRePassSpanNode.innerHTML = "两次输入密码不一致".fontcolor("red");
					flag = false;
				}
			}
			
			//校验邮件
			function checkMail(){
				
				var reg = /^\w+@\w+(\.\w+)+$/;
				check("mail",reg,"mailspan","邮件地址正确","邮件地址错误");
			}				
			
		</script>
		
		<form>
			
			用户名称:<input type="text" name="user" onblur="checkUser()" />
			<span id="userspan"></span>
			<br />
			
			输入密码:<input type="text" name="psw" onblur="checkPsw()" />
			<span id="pswspan"></span>
			<br />
			
			确认密码:<input type="text" name="repsw" onblur="checkRePsw()" />
			<span id="repswspan"></span>
			<br />
			
			邮件地址:<input type="text" name="mail" onblur="checkMail()" />
			<span id="mailspan"></span>
			<br />
			
		</form>
	</body>
</html>

你可能感兴趣的:(DOM(三)-10-(示例-表单校验-涉及的正则校验))