<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<form action="../0620/lunbo.html" method="post">
<div>
<div>
<div>
请输入用户名:
</div>
<div>
<input type="text" name="uid" id="uid" onblur="yanzheng()"/>
<span id="tishi"></span>
</div>
</div>
<div>
<div>
请输入密码:
</div>
<div>
<input type="password" name="uid1" id="uid1" />
</div>
</div>
<div>
<div>
请再次输入密码:
</div>
<div>
<input type="password" name="uid2" id="uid2" onblur="xiangdeng()"/>
<span id="tish2"></span>
</div>
</div>
<div>
<div>
请输入年龄:
</div>
<div>
<input type="text" name="age" id="age" onblur="nage()"/>
<span id="tish3"></span>
</div>
</div>
<div>
<div>
请输入手机号:
</div>
<div>
<input type="text" name="tel" id="tel" onblur="tell()"/>
<span id="tish4"></span>
</div>
</div>
<div>
<div>
<!--双引号里可以直接写js代码,所以可以用return-->
<input type="submit" value="提交" onclick="return check()"/>
</div>
</div>
</div>
</form>
</body>
</html>
<script>
//先执行点击事件,在执行提交
function check(){
//判断如果没有输入即用户名为空,提示用户名为空并返回false,如果不为空返回true
if(document.getElementById("uid").value==""){
alert("用户名不能为空!");
return false;
}else{
return true;
}
}
function yanzheng(){
//非空验证
if(document.getElementById("uid").value==""){
//给后面的span添加文本并改变文本颜色
document.getElementById("tishi").innerText="用户名不能为空";
document.getElementById("tishi").style.color="red";
}else{
document.getElementById("tishi").innerText="用户名可用";
document.getElementById("tishi").style.color="green";
}
}
function xiangdeng(){
var p1=document.getElementById(‘uid1‘);
var p2=document.getElementById(‘uid2‘);
//相等验证
if(p1.value==p2.value){
document.getElementById("tish2").innerText="输入正确";
document.getElementById("tish2").style.color="green";
}else{
document.getElementById("tish2").innerText="两次输入密码不一致";
document.getElementById("tish2").style.color="red";
}
}
function nage(){
var a = document.getElementById("age");
//范围验证
//获取用户输入的值并用parseInt转换为整数进行比较
if(parseInt(a.value)>=18 && parseInt(a.value)<=50){
document.getElementById("tish3").innerText="输入正确";
document.getElementById("tish3").style.color="green";
}else{
document.getElementById("tish3").innerText="年龄不符合条件";
document.getElementById("tish3").style.color="red";
}
}
function tell(){
var a = document.getElementById("tel");
//正则验证
if(a.value.match(/^1[3|4|5|7|8][0-9]{9}$/)==null){
document.getElementById("tish4").innerText="手机号不合法";
document.getElementById("tish4").style.color="red";
}else{
document.getElementById("tish4").innerText="输入正确";
document.getElementById("tish4").style.color="green";
}
}
</script>原文:http://www.cnblogs.com/dongtian1992/p/7067540.html