表单验证,简单封装

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>表单验证</title>
	<style type="text/css">
*{
	margin:0;
	padding:0;
}
.tips {
	padding-top: 30px;
}
		.tips .tip{
		position: fixed;
	        top: 0;
	        z-index: 3;
	        width: 100%;
	        display: none;
	        font-size: px2rem(24);
	        text-align: center;
	        border: 1px solid #f9cdc9;
	        background-color: #feeeea;
	        color: red;
		}



	</style>
</head>
<body>
<div class="tips">
	<p id="tip1" class="tip">name</p>
	<p id="tip2" class="tip">email</p>
	<p id="tip3" class="tip">number</p>
	<p id="tip4" class="tip">4</p>
	<p id="tip5" class="tip">5</p>
	<p id="tip6" class="tip">6</p>
	<p id="tip7" class="tip">7</p>
</div>
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type="text" name="number" id="number">
<input type="text" name="">
<input type="text" name="">
<input type="text" name="">

<script type="text/javascript">
	function $(id){
		return document.getElementById(id);
	}
	var len1=document.getElementsByTagName("input").length;
	var len2=document.getElementsByTagName("select").length;
	var len3=document.getElementsByClassName("tip").length;
	var len4=document.getElementsByTagName("textarea").length;
	function is(obj1,obj2,reg){//obj1表单,obj2提示框,reg验证规则
					obj1.onfocus=function(){
						for(var i = 0; i < len1; i++) {
							document.getElementsByTagName("input")[i].style.border = "1px solid #666666";
						}
						for(var j = 0; j < len3; j++) {
							document.getElementsByClassName("tip")[j].style.display = "none";
						}
						for(var k = 0; k < len2; k++) {
							document.getElementsByTagName("select")[k].style.border = "1px solid #666666";
						}
						for(var l = 0; l < len4; l++) {
							document.getElementsByTagName("textarea")[l].style.border = "1px solid #666666";
						}
						obj2.style.display = "none";
						this.style.border="1px solid #999";
					}
					obj1.onblur=function (){
							if(reg.test(this.value)){							
								this.style.border = "1px solid #999";
								obj2.style.display = "none";
							}else{
								this.style.border = "1px solid red";
								obj2.style.display = "block";
							}
						}
				}
var reg1=/^\w+/,
	reg2=/^[A-Za-z0-9]+([-_.'][A-Za-z0-9]+)*@([A-Za-z0-9]+[-.])+[A-Za-z0-9]{2,5}$/,
	reg3=/^\d/;
is($("name"),$("tip1"),reg1);
is($("email"),$("tip2"),reg2);
is($("number"),$("tip3"),reg3);
</script>
</body>
</html>

 

欢迎分享本文,转载请保留出处:前端ABC » 表单验证,简单封装

赞 (2)
分享到:更多 ()

发表评论 0