js使用正则验证表单数据

一个简单的验证列子,代码如下:

<html>
<head>
<title>正则表达式验证表单</title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
	<style type="text/css">
		.valid{color:green;}
		.invalid{color:red;}
	</style>
</head>
<body>
	<h2>表单验证</h2>
	<form method="POST" onsubmit="return checkForm(this)">
		用户名:<input type="text" name="uname" /><i>5-15个字母,数字,下划线,不能以字母开头</i><br>
		QQ:<input type="text" name="qq" /><i>5-12位QQ号</i><br>
		Email:<input type="text" name="email" /><i>正确的电子邮箱</i><br>
		<input type="submit" name="sub" value="提交"/><br>
	</form>
	<p id="info"></p>
	
</body>
</html>
<script>
function checkForm(myForm){
	var info = document.getElementById("info");
	info.innerHTML = "";
	//验证用户名
	var re = /^[a-zA-Z_][0-9a-zA-Z_]{4,14}$/;
	var val = myForm.uname.value;
	if(!re.test(val))
	{
		info.innerHTML += "<span class='invalid'>用户名["+val+"]不合法</span><br>";
	}
	else
	{
		info.innerHTML += "<span class='valid'>用户名["+val+"]合法</span><br>";
	}
	
	//验证qq号
	re = /^[1-9][0-9]{4,11}$/;
	val = myForm.qq.value;
	if(!re.test(val))
	{
		info.innerHTML += "<span class='invalid'>QQ号["+val+"]不合法</span><br>";
	}
	else
	{
		info.innerHTML += "<span class='valid'>QQ号["+val+"]合法</span><br>";
	}
	
	//验证EMAIL
	re = /^[0-9a-zA-Z_]+@[0-9a-zA-Z_]+\.[a-zA-Z]+(\.[a-zA-Z]+)?$/;
	val = myForm.email.value;
	if(!re.test(val))
	{
		info.innerHTML += "<span class='invalid'>email["+val+"]不合法</span><br>";
	}
	else
	{
		info.innerHTML += "<span class='valid'>eamil["+val+"]合法</span><br>";
	}
	
	return false;
}

</script>


你可能感兴趣的:(js,表单,正则)