我在工作中时常使用form验证,在目前的公司做的表单验证用的angular的form组件,对于一个有追求的前端,或者应用在移动端写个form验证,引入angular或者jquery组件等验证,难免显得臃肿,最好是原生js吧,轻量。幸运 的等到这一课,加上之前所学,慢慢融合根据需求,应用到工作项目中。。。

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="智能社 - zhinengshe.com" />
<meta name="copyright" content="智能社 - zhinengshe.com" />
<title>智能社 - www.zhinengshe.com</title>
<style>
input{ border:1px solid #ccc;}
.ok{ border-color:green;}
.error{ border-color:red;}

</style>
<script src="checkForm.js"></script>
<script>


window.onload = function(){
	checkForm("form1");
};
</script>
</head>

<body>

<form id="form1" action="http://www.zhinengshe.com/">
	用户名:<input type="text" name="username" value=""/><br /><br />
	电话号码:<input type="text" name="tel" value="010-84025890"/><br /><br />
	邮箱:<input type="text" name="email" value="chen00jian@sina.com"/><br /><br />
	年龄:<input type="text" name="age" value=""/><br /><br />

	<input type="submit"/>
</form>

</body>
</html>

  

//版权 北京智能社©, 保留所有权利


var json = {
    username:/^[a-z][a-z0-9_\-$]{5,31}$/i,
    tel:/^(0[1-9]\d{1,2}-)?[1-9]\d{6,7}$/,
    email:/^\w+@[a-z0-9\-]+(\.[a-z]{2,6}){1,2}$/i,
    age:/^(1[6-9]|[2-9]\d|100)$/
};


function checkForm(id){

    var oForm = document.getElementById(id);
    var aInput = oForm.children;


    for(var i = 0; i < aInput.length; i++){
        var re = json[aInput[i].name];

        if(re){
            (function(re){
                aInput[i].onblur = function(){

                    checkText(re,this);
                };
            })(re);
        }
    }

    function checkText(re,oText){

        if(re.test(oText.value)){
            oText.className = "ok";
            return true;
        } else {
            oText.className = "error";
            return false;
        }
    }

    oForm.onsubmit = function(){

        var bOk = true;
        for(var i = 0; i < aInput.length; i++){
            var re = json[aInput[i].name];

            if(re){

                if(checkText(re,aInput[i]) == false){
                    bOk = false;
                }
            }
        }

        if(bOk == false){
            return false;
        }

    };

}
View Code

 

posted on 2015-08-25 15:10  高尔础础  阅读(264)  评论(0编辑  收藏  举报