js 表单验证实例

 gspan.html

<html>
<head>
    <title>表单验证实例</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="check.js" type="text/javascript"></script>
    <style>
        span{ font-size:12px; }
        .stats1{ color : #ccc; }
        .stats2{ color :black; }
        .stats3{ color :red; }
        .stats4{ color :green; }

    </style>
</head>
<body>
	<form method="post" action="reg.php" onsubmit="return regs('click')" >
		用户名:<input type="text" name="username" /><span class="stats1">用户名不能为空</span><br/>
		邮箱:<input type="text" name="email" /><span class="stats1">邮箱不能为空</span><br/>
		密码:<input type="password" name="password" /><span class="stats1">密码不能为空</span><br/>
		确认密码:<input type="password" name="chkpass" /><span class="stats1">密码不能为空</span><br/>
		<input type="submit" />
	</form>
</body>
</html>

 

check.js

function gspan(cobj){		//获取表单后的span 标签 显示提示信息
    if (cobj.nextSibling.nodeName != 'SPAN'){
        gspan(cobj.nextSibling);
    } else {
        return cobj.nextSibling;
    }
}

//检查表单 obj【表单对象】, info【提示信息】 fun【处理函数】  click 【是否需要单击, 提交时候需要触发】
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 = regs;		//页面载入完执行

function regs(click){
    var stat = true;		//返回状态, 提交数据时用到
    username = document.getElementsByName('username')[0];
    password = document.getElementsByName('password')[0];
    chkpass = document.getElementsByName('chkpass')[0];
    email = document.getElementsByName('email')[0];
    
    check(username, "用户名的长度在3-20之间", function(val){
        if (val.match(/^\S+$/) && val.length >=3 && 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(chkpass, "确定密码要和上面一致,规则也要相同", function(val){
        if (val.match(/^\S+$/) && val.length >=6 && val.length <=20 && val == password.value){
            return true;
        } else {
            stat = false;
            return false;
        }
    }, click);

    check(email, "请按邮箱规则输入", function(val){
        if (val.match(/\w+@\w+\.\w/)){
            return true;
        } else {
            stat = false;
            return false;
        }
    }, click);
	return stat;
}

 

posted @ 2012-08-04 15:49  前望  阅读(1904)  评论(0编辑  收藏  举报