C#通用数据校验与工具类封装
在C# Web开发中,对用户输入进行严谨的后端校验至关重要。本教程提供一个通用的数据校验与字符串处理工具类,涵盖了数字、浮点数、Email格式的精准匹配,中英文混合长度的智能计算与截取,以及日期验证和HTML安全编码等功能。
核心功能概览
该工具类整合了多种高频使用的验证逻辑,主要解决以下问题:
- 数据格式校验:支持纯数字、正负号数字、浮点数、Email地址及日期字符串的合法性检测。
- 字符集处理:能够区分中英文字符,准确计算混合字符串的视觉长度或字节长度,并进行智能截取(如超长文本显示省略号)。
- 安全与编码:提供HTML实体编码转换,防止XSS攻击;包含基础的SQL注入防护逻辑(截断过长输入)。
- 辅助功能:包括简单的权限位检查、特定字符组成判断等扩展功能。
环境准备
在 .NET Framework 环境下使用此代码,请确保项目已引用以下命名空间:
System.Text.RegularExpressions
System.Web
System.Web.UI.WebControls
第1步:集成数据校验类
目的:将通用的验证方法导入项目中。
操作:新建一个名为 PageValidate.cs 的文件,并替换/添加如下核心代码。该类使用了 static 修饰符,意味着无需实例化即可直接通过类名调用方法。
using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
namespace YourProject.Utilities // 建议修改为您的命名空间
{
public class PageValidate
{
// 预定义的正则表达式对象,提高性能
private static Regex RegNumber = new Regex("^[0-9]+$");
private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$");
private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");
private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
#region 数字类型校验
/// <summary>
/// 检查是否为纯数字
/// </summary>
public static bool IsNumber(string inputData)
{
if (string.IsNullOrEmpty(inputData)) return false;
Match m = RegNumber.Match(inputData);
return m.Success;
}
/// <summary>
/// 检查是否为带符号的数字(整数)
/// </summary>
public static bool IsNumberSign(string inputData)
{
if (string.IsNullOrEmpty(inputData)) return false;
Match m = RegNumberSign.Match(inputData);
return m.Success;
}
/// <summary>
/// 检查是否为浮点数
/// </summary>
public static bool IsDecimal(string inputData)
{
if (string.IsNullOrEmpty(inputData)) return false;
Match m = RegDecimal.Match(inputData);
return m.Success;
}
/// <summary>
/// 检查是否为带符号的浮点数
/// </summary>
public static bool IsDecimalSign(string inputData)
{
if (string.IsNullOrEmpty(inputData)) return false;
Match m = RegDecimalSign.Match(inputData);
return m.Success;
}
#endregion
#region 中文与特殊字符校验
/// <summary>
/// 检测是否包含中文字符
/// </summary>
public static bool IsHasCHZN(string inputData)
{
if (string.IsNullOrEmpty(inputData)) return false;
Match m = RegCHZN.Match(inputData);
return m.Success;
}
/// <summary>
/// 验证Email格式
/// </summary>
public static bool IsEmail(string inputData)
{
if (string.IsNullOrEmpty(inputData)) return false;
Match m = RegEmail.Match(inputData);
return m.Success;
}
#endregion
#region 字符串长度与截取
/// <summary>
/// 计算文本长度,区分中英文:中文算2个长度单位,英文算1个
/// </summary>
public static int Text_Length(string Text)
{
if (string.IsNullOrEmpty(Text)) return 0;
int len = 0;
for (int i = 0; i < Text.Length; i++)
{
byte[] byte_len = Encoding.Default.GetBytes(Text.Substring(i, 1));
if (byte_len.Length > 1)
len += 2; // 中文
else
len += 1; // 英文或其他
}
return len;
}
/// <summary>
/// 根据指定长度截取字符串,中文占两格,超长部分用“..”代替
/// </summary>
public static string GetSubString(string str, int length)
{
if (string.IsNullOrEmpty(str)) return str;
string temp = str;
int j = 0; // 当前累积长度
int k = 0; // 实际截取字符数
for (int i = 0; i < temp.Length; i++)
{
if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
j += 2;
else
j += 1;
if (j <= length)
k += 1;
else
break; // 超过长度停止
}
if (j > length && k < temp.Length)
return temp.Substring(0, k) + "..";
return temp;
}
#endregion
#region 安全与编码处理
/// <summary>
/// HTML编码,用于防止脚本注入
/// </summary>
public static string HtmlEncode(string inputData)
{
return HttpUtility.HtmlEncode(inputData);
}
/// <summary>
/// SQL输入文本安全处理:去除两端空格并按最大长度截断
/// </summary>
public static string SqlText(string sqlInput, int maxLength)
{
if (sqlInput != null)
{
sqlInput = sqlInput.Trim();
if (sqlInput.Length > maxLength)
sqlInput = sqlInput.Substring(0, maxLength);
}
return sqlInput;
}
#endregion
#region 其他实用功能
/// <summary>
/// 尝试解析日期,返回是否成功
/// </summary>
public static bool IsDateTime(string str)
{
try
{
if (!string.IsNullOrEmpty(str))
{
DateTime.Parse(str);
return true;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// 检查字符串是否完全由单一特定字符组成
/// </summary>
public static bool isContainSameChar(string strInput)
{
if (string.IsNullOrEmpty(strInput)) return false;
char firstChar = strInput[0];
Regex reg = new Regex("^([" + firstChar + @"])+$");
Match m = reg.Match(strInput);
return m.Success;
}
#endregion
}
}
第2步:调用示例与结果判断
在完成上述集成后,可以在业务逻辑层(如 Controller 或 Model 方法)中直接调用这些静态方法。
- 数字校验:
bool isNum = PageValidate.IsNumber("12345"); // 返回 True
bool isFloat = PageValidate.IsDecimal("3.14"); // 返回 True
bool isNeg = PageValidate.IsNumberSign("-100"); // 返回 True
- 中英文长度处理:
// 假设 "Hello世界",英文1*5+中文2*2 = 9
int length = PageValidate.Text_Length("Hello世界"); // 返回 9
// 截取前4个长度单位:应为 "Hello.." (H-e-l-l-o 占5格... 注意逻辑是累加直到超过长度)
// 如果长度设为 6,可能结果为 "Hello世.." 取决于具体实现细节
string sub = PageValidate.GetSubString("这是一段很长的中文测试", 8);
// 预期结果类似 "这是一段长.." (每字2格)
- Email 与安全编码:
bool isValid = PageValidate.IsEmail("user@example.com"); // 返回 True
string safeStr = PageValidate.HtmlEncode("<script>"); // 转换为 HTML实体
排错与维护说明
- 依赖问题:此代码强依赖于
System.Web命名空间中的HttpUtility和HttpRequest。如果您的项目是 .NET Core / .NET 5+ 且未引用 Microsoft.AspNetCore.Http,SqlText和FetchInputDigit相关的方法可能需要移除或重构以适应新的HTTP上下文抽象方式。 - 编码一致性:
Text_Length方法使用Encoding.Default(通常在Windows中文环境下为GBK)。如果在Linux或UTF-8服务器环境下运行,中文可能被视为多个字节,导致长度计算偏差。建议统一使用Encoding.UTF8并在获取字节数组时保持一致性。 - 性能优化:正则表达式对象被声明为
static且只读,这在多线程并发调用时是安全的且高效的,避免了重复编译正则表达式的开销。
总结
以上关于C#实现对用户输入数据进行校验的详细内容,更多关于C#数据处理与验证的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









