目录
关于数据验证
范例运行环境
验证设计
JavaScript 方法
设计
实现
调用示例
C# 方法
设计
实现
调用示例
小结
关于数据验证
在 Web 应用的录入界面,数据验证是一项重要的实现功能,数据验证是指确认 Web 控件输入或选择的数据,是否满足数据表数据约束,是否满足应用程序所需要数据约束规则。建立数据库约束可以满足数据验证的应用,但在实际的应用中,我们建议还是在更新信息到数据库前,在应用中执行数据验证,这样可减少错误录入,减少应用程序与数据库之间频繁通信造成的服务器压力。通过有效的数据验证,可以确认写入数据表中的数据是有效且符合预期的。本文我们将介绍如何通过C# 后端及JavaScript 前端对 Web 控件进行数据输入有效性的验证。
范例运行环境
操作系统: Windows Server 2019 DataCenter
.net版本: .netFramework4.7.1 或以上
开发工具:VS2019 C#
验证设计
通过对 Web 服务器控件捆绑自定义属性 checkSchema="" 和 cName="",将自定义的校验类型和中文提示进行赋值,即可完成验证的设置,可实现的校验类型如下图所示:
多个数据校验类型请用“|”进行分隔,如下设计举例:
示例 1:不能为空且必须为日期型数据
<asp:TextBox id="x1" checkSchema="notnull|date" cName="出生日期" runat="server" />
示例 2:必须为身份证号
<asp:TextBox id="x1" checkSchema="idcard" runat="server" />
示例3:必须输入4位的一个整型数
<asp:TextBox id="x1" checkSchema="mustlen4|int" runat="server" />
JavaScript 方法
设计
在前端客户端,使用 JavaScript 方法 simplecheck 进行数据验证,验证通过反回 true,否则为 false,其参数说明如下表:
序号 | 参数名 | 类型 | 说明 |
---|---|---|---|
1 | chkobj | dom元素对象 | 如传递一个 input type="text" 的对象 |
2 | _chkvalue | 字符串值 | dom元素对象的值,如 value 属性值 |
3 | allowAlert | 布尔值 | 当验证错误时是否允许弹出alert提示框,true为允许 |
4 | etip | 字符串值 | 附加的前缀提示信息,后缀为方法提供的定义的错误提示信息 |
实现
simplecheck 方法完整代码如下:
function simplecheck(chkobj, _chkvalue, allowAlert,etip) {check_result = true; check_errid = ''; check_errmsg = '';var _checkSchema = chkobj.getAttribute('checkSchema');var _cName = chkobj.getAttribute('cName');if (_checkSchema.indexOf('ctrim') != -1) { _chkvalue = ctrim(_chkvalue); } var _objlength = _chkvalue.length; if (_checkSchema.indexOf('abslen') != -1) { _objlength = PositionLen(_chkvalue); }var _schemaList = _checkSchema.split('|'); var _reqeustnotnull = false;for (var k = 0; k < _schemaList.length; k++) { if (_schemaList[k].toLowerCase() == 'notnull') { _reqeustnotnull = true; } }if ((!_reqeustnotnull) && (_chkvalue == '')) { return check_result; }for (var j = 0; j < _schemaList.length; j++) {var curSchema = _schemaList[j].toLowerCase(); check_errid = curSchema; var curErrmsg = ''; switch (true) { case curSchema == 'notnull': check_result = isNotNull(_chkvalue); curErrmsg = _cName + '需要填写内容!'; break; case curSchema == 'number': check_result = isNumber(_chkvalue); curErrmsg = _cName + ' 输入的数值不合理,请核对!'; break; case curSchema == 'bnumber': check_result = isBNumber(_chkvalue); curErrmsg = _cName + ' 输入的数值应为>=0的正数,请核对!'; break; case curSchema == 'snumber': check_result = isSNumber(_chkvalue); curErrmsg = _cName + ' 输入的数值应为<0的负数,请核对!'; break; case curSchema == 'date': check_result = isDate(_chkvalue, _cName); check_errid = 'date'; check_errmsg = (check_result ? '' : _cName + ' 输入的日期不合理,请核对!'); curErrmsg = ''; break; case curSchema.indexOf('minlen') != -1: var _slen = parseInt(curSchema.substr('minlen'.length, curSchema.length - 'minlen'.length), 10); if (isNaN(_slen)) { check_result = false; curErrmsg = _cName + ' 输入的最小位数参数不合理,请与软件供应商联系!'; } else { check_result = (_objlength < _slen ? false : true); curErrmsg = _cName + ' 的内容要求最小输入' + _slen + '位,请核对!'; } break; case curSchema.indexOf('maxlen') != -1: var _slen = parseInt(curSchema.substr('maxlen'.length, curSchema.length - 'maxlen'.length), 10); if (isNaN(_slen)) { check_result = false; curErrmsg = _cName + ' 输入的最大位数参数不合理,请与软件供应商联系!'; } else { check_result = (_objlength > _slen ? false : true); curErrmsg = _cName + ' 最大允许输入' + _slen + '位,请核对!'; } break; case curSchema.indexOf('mustlen') != -1: var _slen = parseInt(curSchema.substr('mustlen'.length, curSchema.length - 'mustlen'.length), 10); if (isNaN(_slen)) { check_result = false; curErrmsg = _cName + ' 输入的限制位数参数不合理,请与软件供应商联系!'; } else { check_result = (_objlength != _slen ? false : true); curErrmsg = _cName + ' 的内容输入长度只能是' + _slen + '位,请核对!'; } break; case curSchema == 'time': check_result = validRegs(_chkvalue, /^\d{1,2}:\d{1,2}:\d{1,2}$/); curErrmsg = _cName + ' 输入的时间不合理,请核对。'; break; case curSchema == 'alpha': check_result = isAlpha(_chkvalue); curErrmsg = _cName + ' 只能输入的数字、字母和下划线,请核对。'; break; case curSchema == 'mail': check_result = validRegs(_chkvalue, /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/); curErrmsg = _cName + ' 输入的邮件地址不合理,请核对。'; break; case curSchema == 'phone': check_result = validRegs(_chkvalue, /([a-zA-Z0-9\.-\u4e00-\u9fa5]{8,})$/); curErrmsg = _cName + ' 输入的电话号码不合理,请核对。'; break; case curSchema == 'mobile': check_result = validRegs(_chkvalue, /^1(3[0-9]|5[012356789]|8[056789])\d{8}$/); curErrmsg = _cName + ' 输入的手机号码不合理,请核对。'; break; case curSchema == 'money': check_result = validRegs(_chkvalue, /^\d+(\.\d+)?$/); curErrmsg = _cName + ' 输入的内容不符合货币类型的要求,请核对。'; break; case curSchema == 'zip': check_result = validRegs(_chkvalue, /^[1-9]\d{5}$/); curErrmsg = _cName + ' 输入的邮政编码不合理,请核对。'; break; case curSchema == 'int': check_result = validRegs(_chkvalue, /^[-\+]?\d+$/); curErrmsg = _cName + ' 需要输入一个整数,请核对。'; break; case curSchema == 'en': check_result = validRegs(_chkvalue, /^[A-Za-z]+$/); curErrmsg = _cName + ' 只能输入英文大小写字母,请核对。'; break; case curSchema == 'cn': check_result = validRegs(_chkvalue, /^[\u0391-\uFFE5]+$/); curErrmsg = _cName + ' 只能输入中文,请核对。'; break; case curSchema == 'url': check_result = validRegs(_chkvalue, /([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/); curErrmsg = _cName + ' 输入的网址不合理,请核对。'; break; case curSchema == 'idcard18': rv_result = checkIdcard(_chkvalue); check_result = (rv_result == '' ? true : false); curErrmsg = _cName + rv_result; break; case curSchema == 'idcard15': rv_result = checkIdcard(_chkvalue); check_result = (rv_result == '' ? true : false); curErrmsg = _cName + rv_result; break; case curSchema == 'idcard': rv_result = checkIdcard(_chkvalue); check_result = (rv_result == '' ? true : false); curErrmsg = _cName + rv_result; break; } if (!check_result) {if (curErrmsg != '') { check_errmsg = etip + curErrmsg; } if ((curErrmsg != '') && (allowAlert)) { alert(etip + curErrmsg); return check_result; }}}return check_result;}
验证函数完整代码如下:
function checkIdcard(idcard) {var _idcard = idcard; var Errors = new Array('', '身份证号码位数不对!', '身份证号码出生日期超出范围或含有非法字符!', '身份证号码校验错误!', '身份证地区非法!', '');if (_idcard == '') { return Errors[5]; }var area = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外' }var _idcard, Y, JYM; var S, M; var idcard_array = new Array(); idcard_array = _idcard.split('');if (area[parseInt(_idcard.substr(0, 2))] == null) { return Errors[4]; }switch (_idcard.length) {case 15: if ((parseInt(_idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(_idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(_idcard.substr(6, 2)) + 1900) % 4 == 0)) {ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/;} else {ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/;}if (ereg.test(_idcard)) {var iS = 0; var iW = new Array; iW[0] = 7; iW[1] = 9; iW[2] = 10; iW[3] = 5; iW[4] = 8; iW[5] = 4; iW[6] = 2; iW[7] = 1; iW[8] = 6; iW[9] = 3; iW[10] = 7; iW[11] = 9; iW[12] = 10; iW[13] = 5; iW[14] = 8; iW[15] = 4; iW[16] = 2;var LastCode = '10X98765432'; var perIDNew; perIDNew = _idcard.substr(0, 6); perIDNew += '19'; perIDNew += _idcard.substr(6, 9);for (var i = 0; i < 17; i++) { iS += parseInt(perIDNew.substr(i, 1)) * iW[i]; }var iY = iS % 11; perIDNew += LastCode.substr(iY, 1);return Errors[0];} else {return Errors[2];}break;case 18: if (parseInt(_idcard.substr(6, 4)) % 4 == 0 || (parseInt(_idcard.substr(6, 4)) % 100 == 0 && parseInt(_idcard.substr(6, 4)) % 4 == 0)) {ereg = _idcard.substr(6, 2) == '19' ? /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/ : /^[1-9][0-9]{5}20[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/;} else {ereg = _idcard.substr(6, 2) == '19' ? /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/ : /^[1-9][0-9]{5}20[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/;}if (ereg.test(_idcard)) {S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 + parseInt(idcard_array[9]) * 3;Y = S % 11; M = 'F'; JYM = '10X98765432'; M = JYM.substr(Y, 1); if (M == idcard_array[17]) return Errors[0]; else { return Errors[3]; } } else { return Errors[2]; } break; default: return Errors[1]; break;} }function getid(id) { alert(checkIdcard(id)) }function per18To15(perIDSrc) { rstr = ''; for (var i = 0; i < 17; i++) { if ((i == 6) || (i == 7)) { continue; } rstr += perIDSrc.charAt(i); } return rstr; }function per15To18(perIDSrc) {var iS = 0; var iW = new Array;iW[0] = 7; iW[1] = 9; iW[2] = 10; iW[3] = 5; iW[4] = 8; iW[5] = 4; iW[6] = 2; iW[7] = 1; iW[8] = 6; iW[9] = 3; iW[10] = 7; iW[11] = 9; iW[12] = 10; iW[13] = 5; iW[14] = 8; iW[15] = 4; iW[16] = 2;var LastCode = '10X98765432'; var perIDNew; perIDNew = perIDSrc.substr(0, 6); perIDNew += '19'; perIDNew += perIDSrc.substr(6, 9);for (var i = 0; i < 17; i++) { iS += parseInt(perIDNew.substr(i, 1)) * iW[i]; }var iY = iS % 11; perIDNew += LastCode.substr(iY, 1); return perIDNew;}var aCity = { 11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外' }function cidInfo(sId) {var iSum = 0; var info = '';if (!/^\d{17}(\d|x)$/i.test(sId))return false; sId = sId.replace(/x$/i, 'a');if (aCity[parseInt(sId.substr(0, 2))] == null) return 'Error:非法地区'; sBirthday = sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2));var d = new Date(sBirthday.replace(/-/g, '/'))if (sBirthday != (d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()))return 'Error:非法生日';for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11)if (iSum % 11 != 1) return 'Error:非法证号';return aCity[parseInt(sId.substr(0, 2))] + ',' + sBirthday + ',' + (sId.substr(16, 1) % 2 ? '男' : '女')}
function PositionLen(s){var i,str1,str2,str3,nLen; str1 =s;nLen = 0;for(i=1;i<=str1.length;i++){str2=str1.substring(i-1,i);str3=escape(str2);if(str3.length>3){ nLen = nLen + 2;}else{nLen = nLen + 1;} }
return nLen;}
function isNotNull(str){return (str==''?false:true);}
function isNumber(str){if(str==''){return true;}return (isNaN(str)?false:true);}
function isNumber(str){if(str==''){return true;}return (isNaN(str)?false:true);}
function isBNumber(str){if(str==''){return true;}return (!isNaN(str)?parseInt(str,10)>=0?true:false:false);}
function isSNumber(str){if(str==''){return true;}return (!isNaN(str)?parseInt(str,10)<0?true:false:false);}
function isAlpha(_str){return (_str.replace(/\w/g,'').length == 0);}
function isAN(_str){var reg = /^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i;return reg.test(_str);}
function validRegs(_value,_Regs){return _Regs.test(_value); }
function isVisibled(obj){ if( (obj.style.display=='none')||( (obj.offsetHeight==0)&&(obj.offsetWidth==0) ) ) return false; if(obj.currentStyle){if(obj.currentStyle['display']=='none') return false;} return true;}
function isFocused(obj){ if( (obj.disabled==false)&&(isVisibled(obj)) ) return true; return false;}
function isDate(str,cname,notip){if(str==''){return true;}
str=str.replace(/\//g,'-');
dt=str.split(' ');if(dt.length>2){if(!notip) alert(cname+'日期输入不正确!可能包括非法的日期组成部分。');return false; } dt1=dt[0].split('-');if(dt1.length!=3){if(!notip) alert(cname+'日期输入不正确!日期部分应为YYYY-MM-DD。');return false;}dt1n=(dt1[0]+dt1[1]+dt1[2]).split('');for(var i=0;i<dt1.length;i++){if((isNaN(dt1[i])||(ctrim(dt1[i])==''))){if(!notip) alert(cname+'字符:'+dt1[i]+',年月日部分必须输入数字!'); return false;} }_year=parseInt(dt1[0],10); _month=parseInt(dt1[1],10); _day=parseInt(dt1[2],10);if((_year<1000)||(_year>9999)||(_month<1)||(_month>12)||(_day<1)||(_day>31)){if(!notip) alert(cname+'年月日部分输入的数字不合理,请核对!');return false; }v_date31=new Array;v_date31[0]=4;v_date31[1]=6;v_date31[2]=9;v_date31[3]=11;if((getArrayIndex(v_date31,_month)!=-1)&&(_day>30)){if(!notip) alert(cname+'月份:'+_month+',天数输入范围不合理!'); return false;}if(_month==2){ if(((_year%4==0)&&(_year%100!=0))||(_year%400==0)){ if(_day>29){if(!notip) alert(cname+'月份:'+_month+',天数输入范围不合理!');return false; }}else{ if(_day>28){if(!notip) alert(cname+'月份:'+_month+',天数输入范围不合理!');return false; }} } return true; }
function getArrayIndex(xArray,find){_rs=-1;for(var j=0;j<xArray.length;j++){if(xArray[j]==find){_rs=j; break; }} return _rs; }
function ctrim(ename){ if(ename==undefined) return ''; return (ename.replace(/(^\s*)|(\s*$)/g, '')).replace(/^[\s \t]+|[\s \t]+$/, '');}
调用示例
假设对 id 为 x1 的输入框元素进行身份证号验证,代码如下:
if(simplecheck(document.getElementById('x1'),document.getElementById('x1').value, true,"您输入的")==false){return false;
}
C# 方法
设计
客户端检验一般属于弱检验,为保证数据的安全合法性,还需要在后端服务端进行二次检验,使用 C# 方法 checkSchemaServerValid 进行数据验证,验证通过返回空字符串信息,否则返回错误提示信息,其参数说明如下表:
序号 | 参数名 | 类型 | 说明 |
---|---|---|---|
1 | value | string | 要校验的数据值 |
2 | _checkSchema | string | 传递校验方案,即传递 Web 控件的自定义 checkSchema 属性值 |
3 | _cName | string | 中文说明,即传递 web 控件的自定义 cName 属性值 |
实现
simplecheck 方法完整代码如下:
public string checkSchemaServerValid(string value,string _checkSchema,string _cName){serverValidErrorType = "";string check_errmsg = "";_checkSchema=_checkSchema.ToLower();if (_checkSchema.IndexOf("ctrim") != -1) { value = value.Trim(); }int _objlength = value.Length;if (_checkSchema.IndexOf("notnull") == -1 && _objlength == 0) { return check_errmsg; }string[] _schemaList = _checkSchema.Split('|');for (var j = 0; j < _schemaList.Length; j++) {string curSchema = _schemaList[j]; string curErrmsg="";if(curSchema=="notnull") { curErrmsg = isNotNull(value)?"":_cName + "需要填写内容!";}else if(curSchema=="number") {curErrmsg =IsNumeric(value)?"":_cName + " 输入的数值不合理,请核对!"; }else if(curSchema=="bnumber") {curErrmsg = IsBNumeric(value)?"":_cName +" 输入的数值应为>=0的正数,请核对!"; }else if(curSchema=="snumber") {curErrmsg = IsSNumeric(value)?"":_cName + " 输入的数值应为<0的负数,请核对!"; }else if(curSchema=="date") {curErrmsg = IsDate(value)?"": _cName + " 输入的日期不合理,请核对!"; }else if(curSchema.IndexOf("minlen")!=-1) {int _slen =int.Parse(curSchema.Substring("minlen".Length, curSchema.Length - "minlen".Length));curErrmsg= value.Length>= _slen ? "": _cName + " 的内容要求最小输入" + _slen.ToString() + "位,请核对!";}else if(curSchema.IndexOf("maxlen")!=-1) {int _mlen =int.Parse(curSchema.Substring("maxlen".Length, curSchema.Length - "maxlen".Length));curErrmsg= value.Length<= _mlen ? "": _cName + " 的内容要求最大输入" + _mlen.ToString() + "位,请核对!";}else if(curSchema.IndexOf("mustlen")!=-1) {int _mlen =int.Parse(curSchema.Substring("mustlen".Length, curSchema.Length - "mustlen".Length));curErrmsg= value.Length== _mlen ? "": _cName + " 的内容输入长度只能是" + _mlen.ToString() + "位,请核对!";}else if(curSchema=="time"){curErrmsg = IsDate(value)?"": _cName + " 输入的时间不合理,请核对!"; }else if(curSchema=="alpha"){curErrmsg =IsAlpha(value)?"": _cName + " 只能输入的数字、字母和下划线,请核对。";}else if(curSchema=="mail"){curErrmsg =IsEmail(value)?"": _cName + " 输入的邮件地址不合理,请核对。"; }else if(curSchema=="phone"){curErrmsg =IsPhone(value)?"": _cName + " 输入的电话号码不合理,请核对。";}else if(curSchema=="mobile"){curErrmsg =IsMobilePhone(value)?"":_cName + " 输入的手机号码不合理,请核对。";}else if(curSchema=="money"){curErrmsg =IsNumeric(value)?"": _cName + " 输入的内容不符合货币类型的要求,请核对。";}else if(curSchema=="zip"){curErrmsg =IsZip(value)?"": _cName + " 输入的邮政编码不合理,请核对。";}else if(curSchema=="int"){curErrmsg =IsInt(value)?"": _cName + " 需要输入一个整数,请核对。";}else if(curSchema=="en"){curErrmsg =IsEnglish(value)?"":_cName + " 只能输入英文大小写字母,请核对。";}else if(curSchema=="cn"){curErrmsg =IsChineseCh(value)?"": _cName + " 只能输入中文,请核对。";}else if(curSchema=="url"){curErrmsg =IsURL(value)?"":_cName + " 输入的网址不合理,请核对。";}else if(curSchema=="idcard"){curErrmsg =CheckIDCard(value)?"": _cName + " 请输入合理的15或18位号码。";}else if(curSchema=="idcard18"){curErrmsg =CheckIDCard18(value)?"": _cName + " 请输入合理的18位号码。";}else if(curSchema=="idcard15"){curErrmsg =CheckIDCard(value)?"": _cName + " 请输入合理的15位号码。";}else if (curSchema == "an"){curErrmsg = IsAN(value) ? "" : _cName + " 必须包含数字和字母。";} check_errmsg = curErrmsg; if(check_errmsg!=""){serverValidErrorType = curSchema;break;}}return check_errmsg;}
C#验证函数完整代码如下:
public bool CheckIDCard(string idNumber){if (idNumber.Length == 18){bool check = CheckIDCard18(idNumber);return check;}else if (idNumber.Length == 15){bool check = CheckIDCard15(idNumber);return check;}else{return false;}}/// <summary> /// 18位身份证号码验证 /// </summary> public bool CheckIDCard18(string idNumber){if (idNumber.Length != 18){return false;}long n = 0;if (long.TryParse(idNumber.Remove(17), out n) == false|| n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false){return false;//数字验证 }string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";if (address.IndexOf(idNumber.Remove(2)) == -1){return false;//省份验证 }string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");DateTime time = new DateTime();if (DateTime.TryParse(birth, out time) == false){return false;//生日验证 }string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');char[] Ai = idNumber.Remove(17).ToCharArray();int sum = 0;for (int i = 0; i < 17; i++){sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());}int y = -1;Math.DivRem(sum, 11, out y);if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower()){return false;//校验码验证 }return true;//符合GB11643-1999标准 }public bool CheckIDCard15(string idNumber){if (idNumber.Length != 15){return false;}long n = 0;if (long.TryParse(idNumber, out n) == false || n < Math.Pow(10, 14)){return false;//数字验证 }string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";if (address.IndexOf(idNumber.Remove(2)) == -1){return false;//省份验证 }string birth = idNumber.Substring(6, 6).Insert(4, "-").Insert(2, "-");DateTime time = new DateTime();if (DateTime.TryParse(birth, out time) == false){return false;//生日验证 }return true;} public bool isNotNull(string value){return value.Length==0?false:true;}public bool IsNumeric(string value){return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");}public bool IsBNumeric(string value){if(Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$")==true){return float.Parse(value)>=0?true:false;}return false;}public bool IsSNumeric(string value){if(Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$")==true){return float.Parse(value)<0?true:false;}return false;}public bool IsInt(string value){return Regex.IsMatch(value, @"^[+-]?\d*$");}public bool IsUnsign(string value){return Regex.IsMatch(value, @"^\d*[.]?\d*$");}public bool isTel(string strInput){return Regex.IsMatch(strInput, @"\d{3}-\d{8}|\d{4}-\d{7}");}public bool IsDate(string value){try{DateTime.Parse(value);return true;}catch{return false;}}public bool IsAlpha(string value){return Regex.IsMatch(value, @"^\w+$");}public bool IsEmail(string value){return Regex.IsMatch(value,@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");}/// 匹配3位或4位区号的电话号码,其中区号可以用小括号括起 /// 也可以不用,区号与本地号间可以用连字号或空格间隔, /// 也可以没有间隔public bool IsPhone(string input){string pattern = "^\\(0\\d{2}\\)[- ]?\\d{8}$|^0\\d{2}[- ]?\\d{8}$|^\\(0\\d{3}\\)[- ]?\\d{7}$|^0\\d{3}[- ]?\\d{7}$";Regex regex = new Regex(pattern);return regex.IsMatch(input);}public bool IsMobilePhone(string input){Regex regex = new Regex("^13\\d{9}$");return regex.IsMatch(input);}public bool IsZip(string value){return Regex.IsMatch(value, @"^\d{6}$");}public bool IsEnglish(string input){Regex regex = new Regex("^[A-Za-z]+$");return regex.IsMatch(input);} public bool IsChineseCh(string input){Regex regex = new Regex("^[\u4e00-\u9fa5]+$");return regex.IsMatch(input);}public bool IsURL(string input){string pattern = @"^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$";Regex regex = new Regex(pattern);return regex.IsMatch(input);}public bool CheckIDCard(string idNumber){if (idNumber.Length == 18){bool check = CheckIDCard18(idNumber);return check;}else if (idNumber.Length == 15){bool check = CheckIDCard15(idNumber);return check;}else{return false;}}/// <summary> /// 18位身份证号码验证 /// </summary> public bool CheckIDCard18(string idNumber){if (idNumber.Length != 18){return false;}long n = 0;if (long.TryParse(idNumber.Remove(17), out n) == false|| n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false){return false;//数字验证 }string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";if (address.IndexOf(idNumber.Remove(2)) == -1){return false;//省份验证 }string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");DateTime time = new DateTime();if (DateTime.TryParse(birth, out time) == false){return false;//生日验证 }string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');char[] Ai = idNumber.Remove(17).ToCharArray();int sum = 0;for (int i = 0; i < 17; i++){sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());}int y = -1;Math.DivRem(sum, 11, out y);if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower()){return false;//校验码验证 }return true;//符合GB11643-1999标准 }public bool CheckIDCard15(string idNumber){if (idNumber.Length != 15){return false;}long n = 0;if (long.TryParse(idNumber, out n) == false || n < Math.Pow(10, 14)){return false;//数字验证 }string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";if (address.IndexOf(idNumber.Remove(2)) == -1){return false;//省份验证 }string birth = idNumber.Substring(6, 6).Insert(4, "-").Insert(2, "-");DateTime time = new DateTime();if (DateTime.TryParse(birth, out time) == false){return false;//生日验证 }return true;}
调用示例
假设对 id 为 x1 的输入框元素进行身份证号验证,代码如下:
string rv=checkSchemaServerValid(x1.Text,x1.Attributes["checkSchema"],"身份证号");
if(rv!=""){Response.Write(rv);
}else{Response.Write("校验通过");
}
小结
本方法提供了一些基础的且实用的验证类型方法,我们在实际的应用中,可以通过扩展自定义 checkSchema 属性中提供的验证类型以满足自己的应用。
如何遍历界面需要校验输入字段,可通过 JavaScript 进行控制,这里不再赘述。
感谢您的阅读,希望本文能够对您有所帮助。