* 示例:
<form action="" onSubmit="return validateForm(this)">
UserName: <input type="text" name="username" depends="require" mask="^\w{6,20}$"><br/>
Password: <input type="password" name="password" depends="require"><br/>
RepeatPs: <input type="password" name="repeatps" depends="repeat[password]"><br/>
Birthday: <input type="text" name="birthday" depends="require,date"><br/>
Zipcode: <input type="text" name="zipcode" depends="zipcode"><br/>
Extension: <input type="text" name="extension" mask="^\d{4}$"><br/>
<input type="Submit" value="Submit">
</form>
* depends预定义的关键字请查看程序代码
* 与0.1版相比,更新的功能有:
1. 添加repeat功能
2. depends关键字更易扩展
3. 修正原来带mask的字段同时带有“require”性的问题
*/
function validateForm(theForm){
//预定义的正则表达式,可以根据自己需要修改
//depends关键字包括“require”和"repeat"以及下面列表中的key值。用法见示例
var reMap = {
"date" : /^(\d{2}|\d{4})-(([1-9])|(1[0-2]))-(([1-9])|([12]\d)|(3[01]))$/, //日期format: yyyy-M-d, yy-M-d
"email" : /^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, //信箱
"chinese" : /^[\u4E00-\u9FA5]+$/, //中文
"zipcode" : /^[1-9]\d{5}$/, //邮编
"phone" : /^\d{3}-\d{8}|\d{4}-\d{7}$/, //电话
"mobile" : /^13\d{9}$/, //手机
"currency" : /^\d+(\.\d{1,4})?$/, //货币
"number" : /^\d+$/, //数字
"integer" : ^(-?\d+)(\.\d+)?$, //整数
"float" : /^[-\+]?\d+(\.\d+)?$/ //小数
};
var aForm = theForm;
for(var i=0;i<aForm.all.length;i++){
var aElement = aForm.all[i];
if(aElement.tagName in {"INPUT":null,"TEXTAREA":null}){
var aDepends = aElement.getAttribute("depends");
if(aDepends!=null){
if(aDepends.search("require")>=0 && aElement.value==""){
alert("Field \"" + aElement.name + "\"" + " is required!");
aElement.focus();
return false;
}else if(aElement.value!=""){
var prop
for(prop in reMap){
if(aDepends.search(prop)>=0 && !reMap[prop].test(aElement.value)){
alert("Field \"" + aElement.name + "\"" + " doesn't match " + prop + "!");
aElement.focus();
return false;
}
}
}
if(aDepends.search("repeat")>=0){
repeatFN = aDepends.substring(aDepends.indexOf("[",aDepends.indexOf("repeat"))+1,
aDepends.indexOf("]",aDepends.indexOf("repeat")));
if(aElement.value!=aForm.all[repeatFN].value){
alert("Field \"" + aElement.name + "\"" + " must equal with " + repeatFN + "!");
aForm.all[repeatFN].focus();
return false;
}
}
}
if(aElement.value!="" && aElement.getAttribute("mask")!=null){
var reMask = new RegExp(aElement.mask);
if(!reMask.test(aElement.value)){
alert("Field \"" + aElement.name + "\"" + " doesn't match mask!");
aElement.focus();
return false;
}
}
}
}
return true;
}