1,js代码部分
<script>
/**
* 自动验证表单
* edit by www.jb200.com
*/
(function(){
if(window.addEventListener) window.addEventListener("load",init,false);
else if(window.attachEvent) window.attachEvent("onload",inint);
function init()
{
for (var i=0;i<document.forms.length ;i++ )//页面中所有表单
{
var f=document.forms[i];
var needValidate = false;//是否需要验证
for(var j=0;j<f.elements.length;j++)//表单中所有元素
{
var e=f.elements[j];
if(e.type!="text") continue;
var pattern=e.getAttribute("pattern");//获取正则
var required=e.getAttribute("required")!=null;//是否是必须
if(required && !pattern)
{
pattern='S';
e.setAttribute("pattern",pattern);
}
else{
e.onchange=validateOnChange;
needValidate=true;
}
}
}
if(needValidate) f.onsubmit=validateOnSubmit;
}
function validateOnChange()
{
var textfield=this;
var pattern=textfield.getAttribute("pattern");
var value=this.value;
if(value.search(pattern)== -1) textfield.className="invalid";
else textfield.className="valid";
}
function validateOnSubmit()
{
var invalid=false;
for(var i=0;i<this.elements.length;i++)
{
var e=this.elements[i];
if(e.type="text" && e.onchange == validateOnChange)
{
e.onchange();
if(e.className=="invalid") invalid=true;
}
}
if(invalid){
alert ("呵呵,有错误,请认真核对");
return false;
}
}
})();
<script>
2,在页面中调用: