C#实现对用户输入数据进行校验的类实例
本文实例讲述了C#实现对用户输入数据进行校验的类。分享给大家供大家参考。具体如下:
这个C#类包含了各种常用数据验证的函数,包含验证是否是数字,校验email格式,区分中英文截取字符串,区分中英文计算字符串长度,检测是否包含中文字符,判断是否包含特定字符等
usingSystem; usingSystem.Text; usingSystem.Web; usingSystem.Web.UI.WebControls; usingSystem.Text.RegularExpressions; namespaceDotNet.Utilities { publicclassPageValidate { privatestaticRegexRegNumber=newRegex("^[0-9]+$"); privatestaticRegexRegNumberSign=newRegex("^[+-]?[0-9]+$"); privatestaticRegexRegDecimal=newRegex("^[0-9]+[.]?[0-9]+$"); privatestaticRegexRegDecimalSign=newRegex("^[+-]?[0-9]+[.]?[0-9]+$");//等价于^[+-]?\d+[.]?\d+$ privatestaticRegexRegEmail=newRegex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w英文字母或数字的字符串,和[a-zA-Z0-9]语法一样 privatestaticRegexRegCHZN=newRegex("[\u4e00-\u9fa5]"); publicPageValidate() { } #region数字字符串检查 ///<summary> ///格式化字符串 ///</summary> ///<paramname="inputData">源字符串</param> ///<paramname="formatlevel">0:不做验证|1:sql语句参数|2:存储过程参数|3:EncodeHtml|4:Encode+sql|5:Encode+存储过程</param> ///<returns>返回格式化后的字符串</returns> publicstaticstringFormatString(stringinputData,intformatlevel) { returninputData; } ///<summary> ///检查Request查询字符串的键值,是否是数字,最大长度限制 ///</summary> ///<paramname="req">Request</param> ///<paramname="inputKey">Request的键值</param> ///<paramname="maxLen">最大长度</param> ///<returns>返回Request查询字符串</returns> publicstaticstringFetchInputDigit(HttpRequestreq,stringinputKey,intmaxLen) { stringretVal=string.Empty; if(inputKey!=null&&inputKey!=string.Empty) { retVal=req.QueryString[inputKey]; if(null==retVal) retVal=req.Form[inputKey]; if(null!=retVal) { retVal=SqlText(retVal,maxLen); if(!IsNumber(retVal)) retVal=string.Empty; } } if(retVal==null) retVal=string.Empty; returnretVal; } publicenumCheckType {None,Int,SignInt,Float,SignFloat,Chinese,Mail} ///<summary> ///检测字符串类型 ///</summary> ///<paramname="inputData">输入字符串</param> ///<paramname="checktype">0:不检测|1:数字|2:符号数字|3:浮点数|4:符号浮点|5:中文?|6:邮件?</param> ///<returns></returns> publicstaticboolcheckString(stringinputData,intchecktype) { bool_return=false; switch(checktype) { case0: _return=true; break; case1: _return=IsNumber(inputData); break; case2: _return=IsNumberSign(inputData); break; case3: _return=IsDecimal(inputData); break; case4: _return=IsDecimalSign(inputData); break; case5: _return=IsHasCHZN(inputData); break; case6: _return=IsEmail(inputData); break; default: _return=false; break; } return_return; } ///<summary> ///是否数字字符串 ///</summary> ///<paramname="inputData">输入字符串</param> ///<returns></returns> publicstaticboolIsNumber(stringinputData) { Matchm=RegNumber.Match(inputData); returnm.Success; } ///<summary> ///是否数字字符串可带正负号 ///</summary> ///<paramname="inputData">输入字符串</param> ///<returns></returns> publicstaticboolIsNumberSign(stringinputData) { Matchm=RegNumberSign.Match(inputData); returnm.Success; } ///<summary> ///是否是浮点数 ///</summary> ///<paramname="inputData">输入字符串</param> ///<returns></returns> publicstaticboolIsDecimal(stringinputData) { Matchm=RegDecimal.Match(inputData); returnm.Success; } ///<summary> ///是否是浮点数可带正负号 ///</summary> ///<paramname="inputData">输入字符串</param> ///<returns></returns> publicstaticboolIsDecimalSign(stringinputData) { Matchm=RegDecimalSign.Match(inputData); returnm.Success; } #endregion #region中文检测 ///<summary> ///检测是否有中文字符 ///</summary> ///<paramname="inputData"></param> ///<returns></returns> publicstaticboolIsHasCHZN(stringinputData) { Matchm=RegCHZN.Match(inputData); returnm.Success; } #endregion publicstaticstringGetShortDate(stringdt) { returnConvert.ToDateTime(dt).ToShortDateString(); } #region邮件地址 ///<summary> ///是否是浮点数可带正负号 ///</summary> ///<paramname="inputData">输入字符串</param> ///<returns></returns> publicstaticboolIsEmail(stringinputData) { Matchm=RegEmail.Match(inputData); returnm.Success; } #endregion #region其他 ///<summary> ///检查字符串最大长度,返回指定长度的串 ///</summary> ///<paramname="sqlInput">输入字符串</param> ///<paramname="maxLength">最大长度</param> ///<returns></returns> publicstaticstringSqlText(stringsqlInput,intmaxLength) { if(sqlInput!=null&&sqlInput!=string.Empty) { sqlInput=sqlInput.Trim(); if(sqlInput.Length>maxLength)//按最大长度截取字符串 sqlInput=sqlInput.Substring(0,maxLength); } returnsqlInput; } ///<summary> ///字符串编码 ///</summary> ///<paramname="inputData"></param> ///<returns></returns> publicstaticstringHtmlEncode(stringinputData) { returnHttpUtility.HtmlEncode(inputData); } ///<summary> ///设置Label显示Encode的字符串 ///</summary> ///<paramname="lbl"></param> ///<paramname="txtInput"></param> publicstaticvoidSetLabel(Labellbl,stringtxtInput) { lbl.Text=HtmlEncode(txtInput); } publicstaticvoidSetLabel(Labellbl,objectinputObj) { SetLabel(lbl,inputObj.ToString()); } #endregion #region对于用户权限从数据库中读出的解密过程 publicstaticstringswitch_riddle(strings_ch)//解密 { strings_out,s_temp,temp; inti_len=s_ch.Length; if(i_len==0||s_ch=="") { s_out="0"; } temp=""; s_temp=""; s_out=""; for(inti=0;i<=i_len-1;i++) { temp=s_ch.Substring(i,1); switch(temp) { case"a":s_temp="1010"; break; case"b":s_temp="1011"; break; case"c":s_temp="1100"; break; case"d":s_temp="1101"; break; case"e":s_temp="1110"; break; case"f":s_temp="1111"; break; case"0":s_temp="0000"; break; case"1":s_temp="0001"; break; case"2":s_temp="0010"; break; case"3":s_temp="0011"; break; case"4":s_temp="0100"; break; case"5":s_temp="0101"; break; case"6":s_temp="0110"; break; case"7":s_temp="0111"; break; case"8":s_temp="1000"; break; case"9":s_temp="1001"; break; default:s_temp="0000"; break; } s_out=s_out+s_temp; s_temp=""; } returns_out; } #endregion #region用户权限的加密过程 publicstaticstringswitch_encrypt(strings_ch) { strings_out,s_temp,temp; inti_len=64; if(i_len==0||s_ch=="") { s_out="0000"; } temp=""; s_temp=""; s_out=""; for(inti=0;i<=i_len-1;i=i+4) { temp=s_ch.Substring(i,4); switch(temp) { case"1010":s_temp="a"; break; case"1011":s_temp="b"; break; case"1100":s_temp="c"; break; case"1101":s_temp="d"; break; case"1110":s_temp="e"; break; case"1111":s_temp="f"; break; case"0000":s_temp="0"; break; case"0001":s_temp="1"; break; case"0010":s_temp="2"; break; case"0011":s_temp="3"; break; case"0100":s_temp="4"; break; case"0101":s_temp="5"; break; case"0110":s_temp="6"; break; case"0111":s_temp="7"; break; case"1000":s_temp="8"; break; case"1001":s_temp="9"; break; default:s_temp="0"; break; } s_out=s_out+s_temp; s_temp=""; } returns_out; }//加密 #endregion #region访问权限 publicstaticboolCheckTrue(strings_admin,inta) { strings_temp=""; s_temp=s_admin.Substring(a-1,1);//s_admin为全局变量 if(s_temp==""||s_temp=="1") { returntrue; } else { returnfalse; } } #endregion #region检测字符串长度 ///<summary> ///计算文本长度,区分中英文字符,中文算两个长度,英文算一个长度 ///</summary> ///<paramname="Text">需计算长度的字符串</param> ///<returns>int</returns> publicstaticintText_Length(stringText) { intlen=0; for(inti=0;i<Text.Length;i++) { byte[]byte_len=Encoding.Default.GetBytes(Text.Substring(i,1)); if(byte_len.Length>1) len+=2;//如果长度大于1,是中文,占两个字节,+2 else len+=1;//如果长度等于1,是英文,占一个字节,+1 } returnlen; } #endregion #region字符串长度区分中英文截取 ///<summary> ///截取文本,区分中英文字符,中文算两个长度,英文算一个长度 ///</summary> ///<paramname="str">待截取的字符串</param> ///<paramname="length">需计算长度的字符串</param> ///<returns>string</returns> publicstaticstringGetSubString(stringstr,intlength) { stringtemp=str; intj=0; intk=0; for(inti=0;i<temp.Length;i++) { if(Regex.IsMatch(temp.Substring(i,1),@"[\u4e00-\u9fa5]+")) { j+=2; } else { j+=1; } if(j<=length) { k+=1; } if(j>length) { returntemp.Substring(0,k)+".."; } } returntemp; } #endregion #region页面HTML格式化 publicstaticstringGetHtml(stringsDetail) { Regexr; Matchm; #region处理空格 sDetail=sDetail.Replace(""," "); #endregion #region处理单引号 sDetail=sDetail.Replace("'","'"); #endregion #region处理双引号 sDetail=sDetail.Replace("\"","""); #endregion #regionhtml标记符 sDetail=sDetail.Replace("<","<"); sDetail=sDetail.Replace(">",">"); #endregion #region处理换行 //处理换行,在每个新行的前面添加两个全角空格 r=newRegex(@"(\r\n(( )|)+)(?<正文>\S+)",RegexOptions.IgnoreCase); for(m=r.Match(sDetail);m.Success;m=m.NextMatch()) { sDetail=sDetail.Replace(m.Groups[0].ToString(),"<BR>"+m.Groups["正文"].ToString()); } //处理换行,在每个新行的前面添加两个全角空格 sDetail=sDetail.Replace("\r\n","<BR>"); #endregion returnsDetail; } #endregion #region分页 //publicstaticstringpaging(stringurl,stringpara,intsumpage,intpage) //{ //stringresult=string.Empty; //if(sumpage==1) //{ //returnresult; //} //if(page>sumpage) //{ //page=1; //} //if(sumpage>0) //{ //for(inti=1;i<=sumpage;i++) //{ //if(i==page) //{ //result+=string.Format("<aclass=\"a_page\"href=\"{0}?page={1}{2}\">{3}</a>",newobject[]{url,i.ToString(),para,i.ToString()}); //} //else //{ //result+=string.Format("<ahref=\"{0}?page={1}{2}\">{3}</a>",newobject[]{url,i.ToString(),para,i.ToString()}); //} //} //} //returnresult; //} publicstaticstringpaging(stringurl,stringpara,intsumpage,intpage) { stringresult=string.Empty; if(sumpage==1) { returnresult; } if(sumpage>500) { sumpage=500; } if(page>sumpage) { page=1; } StringBuildersb=newStringBuilder(); if(sumpage>0) { switch(page) { case1: sb.Append(string.Format("<pclass=\"next\"><ahref=\"{0}?page={1}{2}\">{3}</a>",newobject[]{url,page+1,para,"下一页"})); break; default: if(sumpage==page) { sb.Append(string.Format("<pclass=\"next\"><ahref=\"{0}?page={1}{2}\">{3}</a>",newobject[]{url,page-1,para,"上一页"})); } else { sb.Append(string.Format("<pclass=\"next\"><ahref=\"{0}?page={1}{2}\">{3}</a><ahref=\"{4}?page={5}{6}\">{7}</a>", newobject[]{url,page+1,para,"下一页",url,page-1,para,"上一页"})); } break; } sb.Append(string.Format("第{0}/{1}页</p>",newobject[]{page,sumpage})); } returnsb.ToString(); } publicstaticstringpaging(stringurl,stringpara,intsumpage,intpage,System.Web.UI.UserControlmyPaging) { myPaging.Visible=false; stringresult=string.Empty; if(sumpage==1) { returnresult; } if(sumpage>500) { sumpage=500; } if(page>sumpage) { page=1; } StringBuildersb=newStringBuilder(); if(sumpage>0) { myPaging.Visible=true; switch(page) { case1: sb.Append(string.Format("<ahref=\"{0}?page={1}{2}\">{3}</a>",newobject[]{url,page+1,para,"下一页"})); break; default: if(sumpage==page) { sb.Append(string.Format("<ahref=\"{0}?page={1}{2}\">{3}</a>",newobject[]{url,page-1,para,"上一页"})); } else { sb.Append(string.Format("<ahref=\"{0}?page={1}{2}\">{3}</a><ahref=\"{4}?page={5}{6}\">{7}</a>", newobject[]{url,page+1,para,"下一页",url,page-1,para,"上一页"})); } break; } sb.Append(string.Format("第{0}/{1}页",newobject[]{page,sumpage})); } returnsb.ToString(); } publicstaticstringpaging(stringpara,intsumpage,intpage,intcount) { stringresult=string.Empty; if(page>sumpage) { page=1; } StringBuildersb=newStringBuilder(); if(sumpage>0) { if(sumpage!=1) { switch(page) { case1: sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"下一页"})); break; default: if(sumpage==page) { sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page-1,para,"上一页"})); } else { sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a><ahref=\"?page={3}{4}\">{5}</a>", newobject[]{page-1,para,"上一页",page+1,para,"下一页"})); } break; } } sb.Append(string.Format("第{0}/{1}页共{2}条",newobject[]{page,sumpage,count})); } returnsb.ToString(); } publicstaticvoidpaging(stringclinktail,intsumpage,intpage,System.Web.UI.WebControls.Labelpage_view) { if(sumpage>0) { intn=sumpage;//总页数 intx=page;//得到当前页 inti; intendpage; stringpageview="",pageviewtop=""; if(x>1) { pageview+=" <aclass='pl'href='?page=1"+clinktail+"'>第1页</a>|"; pageviewtop+=" <aclass='pl'href='?page=1"+clinktail+"'>第1页</a>|"; } else { pageview+=" <fontcolor='#666666'>第1页</font>|"; pageviewtop+=" <fontcolor='#666666'>第1页</font>|"; } if(x>1) { pageviewtop+="<aclass='pl'href='?page="+(x-1)+""+clinktail+"'>上1页</a>"; } else { pageviewtop+="<fontcolor='#666666'>上1页</font>"; } if(x>((x-1)/10)*10&&x>10) { pageview+="<aclass='pl'href='?page="+((x-1)/10)*10+""+clinktail+"'onclink='returnfalse;'>上10页</a>"; } //if(((x-1)/10)*10+10)>=n) if(((x-1)/10)*10+10>=n) { endpage=n; } else { endpage=((x-1)/10)*10+10; } for(i=((x-1)/10)*10+1;i<=endpage;++i) { if(i==x) { pageview+="<fontcolor='#FF0000'><b>"+i+"</b></font>"; } else { pageview+="<aclass='pl'href='?page="+i+""+clinktail+"'>"+i+"</a>"; } } if(x<n) { pageviewtop+="<aclass='pl'href='?page="+(x+1)+""+clinktail+"'>下1页</a>"; } else { pageviewtop+="<fontcolor='#666666'>下1页</font>"; } if(endpage!=n) { pageview+="<aclass='pl'href='?page="+(endpage+1)+""+clinktail+"'class='pl'onclink='returnfalse;'>下10页</a>|"; } else { pageview+="|"; } if(x<n) { pageview+="<aclass='pl'href='?page="+n+""+clinktail+"'class='pl'>第"+n+"页</a>"; pageviewtop+="|<aclass='pl'href='?page="+n+""+clinktail+"'class='pl'>第"+n+"页</a>"; } else { pageview+="<fontcolor='#666666'>第"+n+"页</font>"; pageviewtop+="|<fontcolor='#666666'>第"+n+"页</font>"; } page_view.Text=pageview.ToString(); } else { page_view.Text=""; } } //带第一页和最后一页 publicstaticstringpaging2(stringpara,intsumpage,intpage,intcount) { stringresult=string.Empty; if(page>sumpage) { page=1; } StringBuildersb=newStringBuilder(); if(sumpage>0) { if(sumpage!=1) { //第一页 sb.Append(string.Format("<ahref=\"?page={0}{1}\"><imgsrc=\"images/first-icon.gif\"border=\"0\"/></a> ",newobject[]{1,para})); switch(page) { case1: //前一页图片 sb.Append(string.Format("<a>{0}</a>",newobject[]{"<imgsrc=\"images/left-icon.gif\"border=\"0\"/>"})); sb.Append(string.Format("<a>上一页</a><ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"下一页"})); //后一页图片 sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"<imgsrc=\"images/right-icon.gif\"border=\"0\"/>"})); break; default: if(sumpage==page) { //前一页图片 sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page-1,para,"<imgsrc=\"images/left-icon.gif\"border=\"0\"/>"})); sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a><a>下一页</a>",newobject[]{page-1,para,"上一页"})); //后一页图片 sb.Append(string.Format("<a>{0}</a>",newobject[]{"<imgsrc=\"images/right-icon.gif\"/>"})); } else { //前一页图片 sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page-1,para,"<imgsrc=\"images/left-icon.gif\"border=\"0\"/>"})); sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a><ahref=\"?page={3}{4}\">{5}</a>", newobject[]{page-1,para,"上一页",page+1,para,"下一页"})); //后一页图片 sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"<imgsrc=\"images/right-icon.gif\"border=\"0\"/>"})); } break; } //最后一页图片 sb.Append(string.Format(" <ahref=\"?page={0}{1}\"><imgsrc=\"images/last-icon.gif\"border=\"0\"/></a> ",newobject[]{sumpage,para})); } sb.Append(string.Format("第{0}页/共{1}页共{2}条",newobject[]{page,sumpage,count})); } returnsb.ToString(); } publicstaticstringpaging3(stringurl,stringpara,intsumpage,intpage,intcount) { stringresult=string.Empty; if(page>sumpage) { page=1; } StringBuildersb=newStringBuilder(); if(sumpage>0) { if(sumpage!=1) { //第一页 sb.Append(string.Format("<ahref=\"{2}?page={0}{1}\">首页</a>",newobject[]{1,para,url})); switch(page) { case1: //前一页图片 //sb.Append(string.Format("<a>{0}</a>",newobject[]{"<imgsrc=\"images/left-icon.gif\"border=\"0\"/>"})); sb.Append(string.Format("<a>上一页</a><ahref=\"{3}?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"下一页",url})); //后一页图片 //sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"<imgsrc=\"images/right-icon.gif\"border=\"0\"/>"})); break; default: if(sumpage==page) { //前一页图片 //sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page-1,para,"<imgsrc=\"images/left-icon.gif\"border=\"0\"/>"})); sb.Append(string.Format("<ahref=\"{3}?page={0}{1}\">{2}</a><a>下一页</a>",newobject[]{page-1,para,"上一页",url})); //后一页图片 //sb.Append(string.Format("<a>{0}</a>",newobject[]{"<imgsrc=\"images/right-icon.gif\"/>"})); } else { //前一页图片 //sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page-1,para,"<imgsrc=\"images/left-icon.gif\"border=\"0\"/>"})); sb.Append(string.Format("<ahref=\"{6}?page={0}{1}\">{2}</a><ahref=\"{6}?page={3}{4}\">{5}</a>", newobject[]{page-1,para,"上一页",page+1,para,"下一页",url})); //后一页图片 //sb.Append(string.Format("<ahref=\"?page={0}{1}\">{2}</a>",newobject[]{page+1,para,"<imgsrc=\"images/right-icon.gif\"border=\"0\"/>"})); } break; } //最后一页图片 sb.Append(string.Format("<ahref=\"{2}?page={0}{1}\">末页</a> ",newobject[]{sumpage,para,url})); } sb.Append(string.Format("第{0}页/共{1}页共{2}条",newobject[]{page,sumpage,count})); } returnsb.ToString(); } #endregion #region日期格式判断 ///<summary> ///日期格式字符串判断 ///</summary> ///<paramname="str"></param> ///<returns></returns> publicstaticboolIsDateTime(stringstr) { try { if(!string.IsNullOrEmpty(str)) { DateTime.Parse(str); returntrue; } else { returnfalse; } } catch { returnfalse; } } #endregion #region是否由特定字符组成 publicstaticboolisContainSameChar(stringstrInput) { stringcharInput=string.Empty; if(!string.IsNullOrEmpty(strInput)) { charInput=strInput.Substring(0,1); } returnisContainSameChar(strInput,charInput,strInput.Length); } publicstaticboolisContainSameChar(stringstrInput,stringcharInput,intlenInput) { if(string.IsNullOrEmpty(charInput)) { returnfalse; } else { RegexRegNumber=newRegex(string.Format("^([{0}])+$",charInput)); //RegexRegNumber=newRegex(string.Format("^([{0}]{{1}})+$",charInput,lenInput)); Matchm=RegNumber.Match(strInput); returnm.Success; } } #endregion #region检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查 ///<summary> ///检查输入的参数是不是某些定义好的特殊字符:这个方法目前用于密码输入的安全检查 ///</summary> publicstaticboolisContainSpecChar(stringstrInput) { string[]list=newstring[]{"123456","654321"}; boolresult=newbool(); for(inti=0;i<list.Length;i++) { if(strInput==list[i]) { result=true; break; } } returnresult; } #endregion } }
希望本文所述对大家的C#程序设计有所帮助。