例子,javascript表单验证代码。
复制代码 代码示例:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>注册会员_表单验证 - www.jb200.com</title>
<style type="text/css">
.table {
border-collapse:collapse;
font-size:12px;
}
.input {
width:200px;
height:22px;
}
.stats1 {
color:#aaa;
}
.stats2 {
color:#000;
}
.stats3 {
color:red;
}
.stats4 {
color:green;
}
</style>
</head>
<body>
<form action="index.php" method="post" onSubmit="return regCheck('click')">
<table border="0" align="center" width="500" class="table">
<tr>
<td width="80" height="25" align="right">用户名称:</td><td><input type="text" name="username" value="" class="input" /> <span class="stats1"></span></td>
</tr>
<tr>
<td width="80" height="25" align="right">密码:</td><td><input type="password" name="password" value="" class="input" /> <span class="stats1"></span></td>
</tr>
<tr>
<td width="80" height="25" align="right">确认密码:</td><td><input type="password" name="repass" value="" class="input" /> <span class="stats1"></span></td>
</tr>
<tr>
<td width="80" height="25" align="right">电子邮箱:</td><td><input type="text" name="email" value="" class="input" /> <span class="stats1"></span></td>
</tr>
<tr>
<td height="30"></td><td align="left"><input type="submit" name="send" value="提交" /> <input type="reset" value="重置" /></td>
</tr>
</table>
</form>
</body>
</html>
<script language="javascript">
// 找到 input 后面的 SPAN 标签
function gspan(cobj){
while(true){
if(cobj.nextSibling.nodeName!="SPAN")
cobj=cobj.nextSibling;
else
return cobj.nextSibling;
}
}
function check(obj, info, fun, click){
var sp=gspan(obj);
obj.onfocus=function(){
sp.innerHTML=info;
sp.className="stats2";
}
obj.onblur=function(){
if(fun(this.value)){
sp.innerHTML="输入正确√";
sp.className="stats4";
}else{
sp.innerHTML=info;
sp.className="stats3";
}
}
if(click=="click")
obj.onblur();
}
//页面加载完自动调用
onload=regCheck
function regCheck(click){
var stat=true;
var username=document.getElementsByName("username")[0];
var password=document.getElementsByName("password")[0];
var repass=document.getElementsByName("repass")[0];
var email=document.getElementsByName("email")[0];
var other=document.getElementsByName("other")[0];
// 验证用户名
check(username, "用户名称为4-20位的英文字母或数字!", function(val){
if(val.match(/^S+$/) && val.length >=4 && val.length <=20){
return true;
}else{
stat=false;
return false;
}
}, click);
// 验证密码
check(password, "用户密码必须在6-20位之间!", function(val){
if(val.match(/^S+$/) && val.length >=6 && val.length <=20){
return true;
}else{
stat=false;
return false;
}
}, click);
// 验证确认密码
check(repass, "确定密码要和上面一致!", function(val){
if(val.match(/^S+$/) && val.length >=6 && val.length <=20 && val==password.value){
return true;
}else{
stat=false;
return false;
}
}, click)
// 验证Email
check(email, "请输入正确格式的电子邮箱!", function(val){
if(val.match(/w+@w+.w/)){
return true;
}else{
stat=false;
return false;
}
}, click)
return stat;
}
</script>