首页 > 代码库 > js 验证年龄 姓名

js 验证年龄 姓名

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"   http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>

<meta http-equiv = "content-type" content="text/html;charset=utf-8"/>

<script src="http://www.mamicode.com/js.js" type="text/javascript" language="javascript">

</script>

</head>

<body>

<form>

姓名:<input type = "text" id = "name" onblur = "checkname();" />

<span id = "s1">请输入3-5个字母</span><br />

年龄:<input type = "text" id = "age" onblur = "checkage();"/>

  <span id = "s2">请输入2位数字</span>

   <input type = "submit" value = "http://www.mamicode.com/提交" onclick = "return valid();"/>

</form>

</body>

</html>

//js.js

function checkname(){
	var name = document.getElementById("name").value;
	var s1 = document.getElementById("s1");
	var regname = /^[a-zA-Z]{3,5}$/;///定义一个RegExp对象
	if(regname.test(name)){//使用RegExp对象的方法验证
		s1.innerHTML = "录入正确";
		s1.style.color = "green";
	}else{
		s1.innerHTML = "录入错误";
		s1.style.color = "red";
	}
	return regname.test(name);
}
function checkage(){
	var age = document.getElementById("age").value;
	var s2 = document.getElementById("s2");
	var regname = /^\d{2}$/;
	if(regname.test(age)){
		s2.innerHTML = "录入正确";
		s2.style.color = "green";

	}else{
		s2.innerHTML = "录入错误";
		s2.style.color = "red";
	}
	return regname.test(name);
}
function valid(){
	return checkname()&& checkage();
}