killapp/Assets/Scripts/Utils/ValidationUtils.cs

125 lines
4.0 KiB
C#
Raw Normal View History

2026-04-16 14:57:19 +08:00
using System;
using System.Text.RegularExpressions;
namespace Kill.Utils
{
/// <summary>
/// 验证工具类
/// 提供常用的数据验证方法
/// </summary>
public static class ValidationUtils
{
#region
/// <summary>
/// 验证邮箱格式是否有效(正则验证,更严格)
/// </summary>
public static bool IsValidEmailStrict(string email)
{
if (string.IsNullOrEmpty(email))
return false;
// RFC 5322 标准邮箱正则
string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
return Regex.IsMatch(email, pattern);
}
#endregion
#region
/// <summary>
/// 验证简单密码格式6位数字
/// </summary>
public static bool IsValidSimplePassword(string password)
{
if (string.IsNullOrEmpty(password))
return false;
// 6位数字
string pattern = @"^\d{6}$";
return Regex.IsMatch(password, pattern);
}
/// <summary>
/// 验证复杂密码格式6-16位同时包含数字、字母和特殊字符
/// </summary>
public static bool IsValidComplexPassword(string password)
{
if (string.IsNullOrEmpty(password))
return false;
// 长度6-16位
if (password.Length < 6 || password.Length > 16)
return false;
// 必须包含数字
bool hasDigit = Regex.IsMatch(password, @"\d");
// 必须包含字母
bool hasLetter = Regex.IsMatch(password, @"[a-zA-Z]");
// 必须包含特殊字符(支持半角和全角符号)
bool hasSpecial = Regex.IsMatch(password, @"[!@#$%^&*()_+\-=\[\]{};':""\\|,.<>\/?]|\p{P}");
2026-04-16 14:57:19 +08:00
return hasDigit && hasLetter && hasSpecial;
}
/// <summary>
/// 检查是否包含连续或重复的三个及以上数字或字母(大小写不敏感)
/// </summary>
public static bool IsValidNoRepeatOrConsecutive(string password)
{
for (int i = 0; i <= password.Length - 3; i++)
{
char c0 = password[i];
char c1 = password[i + 1];
char c2 = password[i + 2];
if (!char.IsLetterOrDigit(c0) || !char.IsLetterOrDigit(c1) || !char.IsLetterOrDigit(c2))
continue;
bool isRepeated;
if (char.IsLetter(c0))
isRepeated = char.ToLower(c0) == char.ToLower(c1) && char.ToLower(c1) == char.ToLower(c2);
else
isRepeated = c0 == c1 && c1 == c2;
if (isRepeated) return false;
if (char.IsDigit(c0) && char.IsDigit(c1) && char.IsDigit(c2))
{
if ((c1 - c0 == 1 && c2 - c1 == 1) || (c0 - c1 == 1 && c1 - c2 == 1))
return false;
}
else if (char.IsLetter(c0))
{
char l0 = char.ToLower(c0), l1 = char.ToLower(c1), l2 = char.ToLower(c2);
if ((l1 - l0 == 1 && l2 - l1 == 1) || (l0 - l1 == 1 && l1 - l2 == 1))
return false;
}
}
return true;
}
/// <summary>
/// 检查密码是否包含邮箱中任意连续两个字符
/// </summary>
public static bool IsValidNotEmailPart(string password, string email)
{
if (string.IsNullOrEmpty(email)) return true;
string emailName = email;
string pwdLower = password.ToLower();
for (int i = 0; i <= emailName.Length - 2; i++)
{
string pair = emailName.Substring(i, 2).ToLower();
if (pwdLower.Contains(pair))
return false;
}
return true;
}
2026-04-16 14:57:19 +08:00
#endregion
}
}