在客户端进行数据合法性,是保证系统安全,以及提高用户体验的很重的方法。以前基本上都是每个项目自己写,完后再在对应控件中加入事件触发相应方法来完成,这样会发现每次都有很多工作是重复性的,而且写起来也挺麻烦。最近在我们新做的项目采用了一个可以通用,而且使用很方便的客户端验证方法。
它可以验证诸如:
1.是否为空;
2.中文字符;Chinese
3.双字节字符;
4.英文;
5.数字;
6.整数;
7.实数;
8.Email地址;
9.使用HTTP协议的网址;
10.电话号码;
11.货币;
12.手机号码;
13.邮政编码;
14.身份证号码;
15.QQ号码;
16.日期;
17.符合安全规则的密码;
18.某项的重复值;
19.两数的关系比较;
20.判断输入值是否在(n, m)区间;
21.输入字符长度限制(可按字节比较);
22.对于具有相同名称的单选按钮的选中判断;
23.限制具有相同名称的多选按钮的选中数目;
具体代码如下,使用时将它保存为一个文件,完后引用到页面。在要验证的组中做添加相应属性即可如:
<asp:TextBox ID="txtStartMonth" runat="server" dataType="Date" format="ym" MaxLength="7" msg="请输入有效的年月,如2005-08。">
完后,再给提交按钮加入对验证的触发事件:ibtOK .Attributes["onclick"] = "javascript:if(!Validator.Validate(document.forms[0],2)) return false;"。
看到没,使用就是如此之简单。
-------------------------------------------------------
Validator = {
Require : /.+/,
Email : /^/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*$/,
Phone : /^((/(/d{2,3}/))|(/d{3}/-))?(/(0/d{2,3}/)|0/d{2,3}-)?[1-9]/d{6,7}(/-/d{1,4})?$/,
Mobile : /^((/(/d{2,3}/))|(/d{3}/-))?13/d{9}$/,
Url : /^http:[A-Za-z0-9]+/.[A-Za-z0-9]+[//=/?%/-&_~`@[/]/':+!]*([^<>/"/"])*$/,
IdCard : "this.IsIdCard(value)",
Currency : /^/d+(/./d+)?$/,
Number : /^/d+$/,
Zip : /^[1-9]/d{5}$/,
QQ : /^[1-9]/d{4,8}$/,
Integer : /^[-/+]?/d+$/,
Double : /^[-/+]?/d+(/./d+)?$/,
English : /^[A-Za-z]+$/,
Chinese : /^[/u0391-/uFFE5]+$/,
Username : /^[a-z]/w{3,}$/i,
UnSafe : /^(([A-Z]*|[a-z]*|/d*|[-_/~!@#/$%/^&/*/./(/)/[/]/{/}<>/?/'/"]*)|.{0,5})$|/s/,
IsSafe : function(str){return !this.UnSafe.test(str);},
SafeString : "this.IsSafe(value)",
Filter : "this.DoFilter(value, getAttribute('accept'))",
Limit : "this.limit(value.length,getAttribute('min'), getAttribute('max'))",
LimitB : "this.limit(this.LenB(value), getAttribute('min'), getAttribute('max'))",
Date : "this.IsDate(value, getAttribute('format'))",
Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",
Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')",
Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",
Custom : "this.Exec(value, getAttribute('regexp'))",
Group : "this.MustChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
ErrorItem : [document.forms[0]],
ErrorMessage : ["以下原因导致提交失败:/t/t/t/t/n"],
Validate : function(theForm, mode){
var obj = theForm || event.srcElement;
var count = obj.elements.length;
this.ErrorMessage.length = 1;
this.ErrorItem.length = 1;
this.ErrorItem[0] = obj;
for(var i=0;i<count;i++){
with(obj.elements[i]){
var _dataType = getAttribute("dataType");
if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") continue;
this.ClearState(obj.elements[i]);
if(getAttribute("require") == "false" && value == "") continue;
switch(_dataType){
case "IdCard" :
case "Date" :
case "Repeat" :
case "Range" :
case "Compare" :
case "Custom" :
case "Group" :
case "Limit" :
case "LimitB" :
case "SafeString" :
case "Filter" :
if(!eval(this[_dataType])) {
this.AddError(i, getAttribute("msg"));
}
break;
default :
if(!this[_dataType].test(value)){
this.AddError(i, getAttribute("msg"));
}
break;
}
}
}
if(this.ErrorMessage.length > 1){
mode = mode || 1;
var errCount = this.ErrorItem.length;
switch(mode){
case 2 :
for(var i=1;i<errCount;i++)
this.ErrorItem[i].style.color = "red";
case 1 :
alert(this.ErrorMessage.join("/n"));
this.ErrorItem[1].focus();
break;
case 3 :
for(var i=1;i<errCount;i++){
try{
var span = document.createElement("SPAN");
span.id = "__ErrorMessagePanel";
span.style.color = "red";
this.ErrorItem[i].parentNode.appendChild(span);
span.innerHTML = this.ErrorMessage[i].replace(//d+:/,"*");
}
catch(e){alert(e.description);}
}
this.ErrorItem[1].focus();
break;
default :
alert(this.ErrorMessage.join("/n"));
break;
}
return false;
}
return true;
},
limit : function(len,min, max){
min = min || 0;
max = max || Number.MAX_VALUE;
return min <= len && len <= max;
},
LenB : function(str){
return str.replace(/[^/x00-/xff]/g,"**").length;
},
ClearState : function(elem){
with(elem){
if(style.color == "red")
style.color = "";
var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
if(lastNode.id == "__ErrorMessagePanel")
parentNode.removeChild(lastNode);
}
},
AddError : function(index, str){
this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + "、" + str;
},
Exec : function(op, reg){
return new RegExp(reg,"g").test(op);
},
compare : function(op1,operator,op2){
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
}
},
MustChecked : function(name, min, max){
var groups = document.getElementsByName(name);
var hasChecked = 0;
min = min || 1;
max = max || groups.length;
for(var i=groups.length-1;i>=0;i--)
if(groups[i].checked) hasChecked++;
return min <= hasChecked && hasChecked <= max;
},
DoFilter : function(input, filter){
return new RegExp("^.+/.(?=EXT)(EXT)$".replace(/EXT/g, filter.split(//s*,/s*/).join("|")), "gi").test(input);
},
IsIdCard : function(number){
if (number)
number = number.toUpperCase();
var date, Ai;
var verify = "10X98765432";
var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外'];
var re = number.match(/^(/d{2})/d{4}(((/d{2})(/d{2})(/d{2})(/d{3}))|((/d{4})(/d{2})(/d{2})(/d{3}[x/d])))$/i);
if(re == null) return false;
if(re[1] >= area.length || area[re[1]] == "") return false;
if(re[2].length == 12){
Ai = number.substr(0, 17);
date = [re[9], re[10], re[11]].join("-");
}
else{
Ai = number.substr(0, 6) + "19" + number.substr(6);
date = ["19" + re[4], re[5], re[6]].join("-");
}
if(!this.IsDate(date, "ymd")) return false;
var sum = 0;
for(var i = 0;i<=16;i++){
sum += Ai.charAt(i) * Wi[i];
}
Ai += verify.charAt(sum%11);
return (number.length ==15 || number.length == 18 && number == Ai);
},
IsDate : function(op, formatString){
formatString = formatString || "ymd";
var m, year, month, day;
switch(formatString){
case "ymd" :
m = op.match(new RegExp("^(//d{4})-(//d{2})-(//d{2})$"));
if(m == null ) return false;
day = m[3];
month = m[2]*1;
year = m[1];
break;
case "ym" :
m = op.match(new RegExp("^(//d{4})-(//d{2})$"));
if(m == null ) return false;
day = 1;
month = m[2]*1;
year = m[1];
break;
case "dmy" :
m = op.match(new RegExp("^(//d{2})-(//d{2})-(//d{4})$"));
if(m == null ) return false;
day = m[1];
month = m[2]*1;
year = m[3];
break;
default :
break;
}
if(!parseInt(month)) return false;
month = month==0 ?12:month;
var date = new Date(year, month-1, day);
return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
}
}