using System.Text; namespace ClassNotify.Shared.Validation; public static class ClassNameValidator { public const string RuleDescription = "班级名称不允许包含除“班”以外的汉字(推荐格式如:81班、82、83、84、89、810班)"; /// /// 校验班级名称是否合法: /// 1. 不可为空 /// 2. 长度在 1~30 之间 /// 3. 使用 Rune 遍历 Unicode scalar,全面覆盖基本 CJK、扩展 A~I 与兼容区,除单字“班”外严禁任何汉字 /// public static (bool IsValid, string? ErrorMessage) Validate(string? className) { if (string.IsNullOrWhiteSpace(className)) { return (false, "班级名称不可为空"); } var trimmed = className.Trim(); if (trimmed.Length > 30) { return (false, "班级名称长度不能超过30个字符"); } foreach (var rune in trimmed.EnumerateRunes()) { int cp = rune.Value; if (IsHan(cp) && cp != '班') { return (false, RuleDescription); } } return (true, null); } /// /// 全面判断 Unicode code point 是否属于汉字 (CJK 表意字符集及各扩展区块) /// public static bool IsHan(int codePoint) { return (codePoint >= 0x4E00 && codePoint <= 0x9FFF) || // CJK Unified Ideographs (含 U+9FA6~U+9FFF) (codePoint >= 0x3400 && codePoint <= 0x4DBF) || // CJK Extension A (codePoint >= 0x20000 && codePoint <= 0x2A6DF) || // CJK Extension B (codePoint >= 0x2A700 && codePoint <= 0x2B73F) || // CJK Extension C (codePoint >= 0x2B740 && codePoint <= 0x2B81F) || // CJK Extension D (codePoint >= 0x2B820 && codePoint <= 0x2CEAF) || // CJK Extension E (codePoint >= 0x2CEB0 && codePoint <= 0x2EBEF) || // CJK Extension F (codePoint >= 0x30000 && codePoint <= 0x3134F) || // CJK Extension G (codePoint >= 0x31350 && codePoint <= 0x323AF) || // CJK Extension H (codePoint >= 0x2EBF0 && codePoint <= 0x2EE5F) || // CJK Extension I (codePoint >= 0xF900 && codePoint <= 0xFAFF) || // CJK Compatibility Ideographs (codePoint >= 0x2F800 && codePoint <= 0x2FA1F); // CJK Compatibility Ideographs Supplement } }