using System.Text.RegularExpressions; namespace Common.Utils { public static class ValidationHelper { private static readonly Regex MobileRegex = new(@"^1[3-9]\d{9}$", RegexOptions.Compiled); private static readonly Regex IdCardRegex = new(@"^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$", RegexOptions.Compiled); private static readonly Regex UserNameRegex = new(@"^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$", RegexOptions.Compiled); public static bool IsValidMobile(string mobile) { if (string.IsNullOrWhiteSpace(mobile)) return false; return MobileRegex.IsMatch(mobile); } public static bool IsValidIdCard(string idCard) { if (string.IsNullOrWhiteSpace(idCard) || idCard.Length != 18) return false; if (!IdCardRegex.IsMatch(idCard)) return false; return ValidateIdCardCheckSum(idCard); } public static bool IsValidUserName(string userName) { if (string.IsNullOrWhiteSpace(userName)) return false; return UserNameRegex.IsMatch(userName); } public static bool IsPositiveAmount(long amount) { return amount > 0; } public static bool IsPositiveAmount(int amount) { return amount > 0; } public static bool IsInRange(int count, int min, int max) { return count >= min && count <= max; } public static bool IsValidLength(string value, int minLength, int maxLength) { if (string.IsNullOrWhiteSpace(value)) return false; return value.Length >= minLength && value.Length <= maxLength; } public static bool IsValidPassword(string password) { if (string.IsNullOrWhiteSpace(password) || password.Length < 6 || password.Length > 20) return false; return password.Any(char.IsLetter) && password.Any(char.IsDigit); } private static bool ValidateIdCardCheckSum(string idCard) { int[] weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; char[] checkCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' }; int sum = 0; for (int i = 0; i < 17; i++) { sum += (idCard[i] - '0') * weight[i]; } char expectedCheckChar = checkCodes[sum % 11]; char actualCheckChar = char.ToUpper(idCard[17]); return expectedCheckChar == actualCheckChar; } } }