日期:2014-05-19  浏览次数:20906 次

求过滤输入的算法
毕业工作的第一个任务:
写一个输入校验的类,对输入框输入的信息进行过滤,过滤的内容包括恶意脚本和国家要求严格控制的文字词组等,要与目前系统结合起来。方法可能有多种,要取一种使原系统改动最小的方法  
分不多,实在寒酸,还请大家给点建议!

------解决方案--------------------
以下是我写的一个类,有用就拿去用吧
using System;
using System.Text.RegularExpressions;

namespace TxtManage
{
/// <summary>
/// StrRgeExp 的摘要说明。
/// </summary>
public class StrRgeExp
{
public StrRgeExp()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

/// <summary>
/// 验证字符串是否为Email格式
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsEmail(string s)
{
string pattern = @ "^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$ ";
return Regex.IsMatch(s, pattern);
}

/// <summary>
/// 验证字符串是否为IP格式
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsIp(string s)
{
string pattern = @ "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ ";
return Regex.IsMatch(s, pattern);
}

/// <summary>
/// 验证字符串是否为数字格式(无论正负)
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsNumeric(string s)
{
string pattern = @ "^\-?[0-9]+$ ";
return Regex.IsMatch(s, pattern);
}


/// <summary>
/// 验证字符串是否为物理路径
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsPhysicalPath(string s)
{
string pattern = @ "^\s*[a-zA-Z]:.*$ ";
return Regex.IsMatch(s, pattern);
}

/// <summary>
/// 验证字符串是否为相对路径
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsRelativePath(string s)
{
if ((s == null) || (s == string.Empty))
{
return false;
}
if (s.StartsWith( "/ ") || s.StartsWith( "? "))
{
return false;
}
if (Regex.IsMatch(s, @ "^\s*[a-zA-Z]{1,10}:.*$ "))
{
return false;
}
return true;
}


/// <summary>
/// 验证字符串是否为安全代码
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsSafety(string s)
{
string input = Regex.Replace(s.Replace( "%20 ", " "), @ "\s ", " ");
string pattern = "select |insert |delete from |count\\(|drop table|update |truncate |asc\\(|mid\\(|char\\(|xp_cmdshell|exec master|net localgroup administrators|:|net user|\ "|\\ '| or ";
return !Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
}

/// <summary>
/// 验证字符串是否为连接
/// </summary>
/// <param name= "s "> string </param>
/// <returns> </returns>
public bool IsUrl(string s)
{
string pattern = @ "^(http|https|ftp|rtsp|mms):(\/\/|\\\\)[A-Za-z0-9%\-_@]+\.[A-Za-z0-9%\-_@]+[A-Za-z0-9\.\/=\?%\-&_~`@:\+!;]*$ ";
return Regex.IsMatch(s, patt