对输入数据的验证

很多的时候需要对用户输入的数据进行验证,才能保证系统的安全性,因为我们无法保证系统的完美而免遭恶意的攻击,同时也是完善系统,确保数据的正确

1.非空验证

代码
/// <summary>是否空</summary>
/// <param name="strInput">输入字符串</param>
/// <returns>true/false</returns>
public static bool IsBlank(string strInput)
{
if (string.IsNullOrEmpty(strInput))
{
return true;
}
else
{
return false;
}
}
2.判断是否是数字

代码
public static bool IsNumeric(string strInput)
{

if (string.IsNullOrEmpty(strInput))
return false;
System.Text.RegularExpressions.Regex reg
= new System.Text.RegularExpressions.Regex(@"^[-]?\d+[.]?\d*$");
return reg.IsMatch(strInput);
}
3.判断时间

代码
public static bool IsDateTime(string strDate)
{
System.Text.RegularExpressions.Regex reg
=
new System.Text.RegularExpressions.Regex(
@"(((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9]))|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29))|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)))((\s+(0?[1-9]|1[012])(:[0-5]\d){0,2}(\s[AP]M))?$|(\s+([01]\d|2[0-3])(:[0-5]\d){0,2})?$))");
return reg.IsMatch(strDate);
}
4.检查年月日是否合法

代码
private static bool CheckDatePart(string year, string month, string day)
{
int iyear = Convert.ToInt16(year);
int imonth = Convert.ToInt16(month);
int iday = Convert.ToInt16(day);
if (iyear > 2099 || iyear < 1900) { return false; }
if (imonth > 12 || imonth < 1) { return false; }
if (iday > DateUtil.GetDaysOfMonth(iyear, imonth) || iday < 1) { return false; };
return true;

}
5.检测邮件的合法性

代码
public static bool IsEmail(string inputEmail)
{
inputEmail
= inputEmail.Trim();
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re
= new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
6.检查正确的http地址

代码
public static bool IsHttpUrl(string inputUrl)
{
inputUrl
= inputUrl.Trim();
Regex re
= new Regex("((^http)|(^https)|(^ftp))://(\\w)+.(\\w)+");
if (re.IsMatch(inputUrl) || re.IsMatch("http://" + inputUrl))
return (true);
else
return (false);
}

posted @ 2010-09-17 12:01  marr  阅读(440)  评论(0编辑  收藏  举报