代码实现:
<!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>
<script>
//初始化页面
function initform(){
//第一个文本框获取焦点
//document.getElementById("username").focus();
//产生验证码
getCode();
}
//产生验证码
function getCode(){
var code = String(Math.round(Math.random()*10000));
while(code.length<4){
code = "0"+code;
}
document.getElementById("newcode").value=code;
}
//剔除空格
function trim(){
return this.replace(/(^s*)|(s*$)/g, "");
}
//显示错误提示
function shouWarn(uid,msg){
document.getElementById(uid).innerHTML=msg;
document.getElementById(uid).style.display="";
}
//清空错误提示
function clearWarn(uid){
document.getElementById(uid).style.display="none";
}
//检验验证码
function checkCode(code,uid){
var checkcode = document.getElementById("newcode").value;
if(checkcode==code){
var msg="<font color='#0F0'>√√√√√</font>";
shouWarn(uid,msg)
return (true);
}else{
msg="<font color='#F00'>验证码输入错误!</font>";
shouWarn(uid,msg);
return (false);
}
}
//验证用户名
function checkUserName(usename,uid){
var uName = usename.trim();
var reg1 = /^[a-zA-Z]{1}[a-zA-Z0-9]{5,19}$/;
if(reg1.test(uName)==true){
var msg="<font color='#0F0'>√√√√√</font>";
shouWarn(uid,msg)
return (true);
}else{
msg="<font color='#F00'>用户名输入不规范!</font>";
shouWarn(uid,msg);
return (false);
}
}
//验证密码
function checkPassword(password,uid){
var pwd = password.trim();
var reg2 = /^[a-zA-Z0-9]{6,20}$/;
if(reg2.test(pwd)==true){