TH1/Unity/Assets/Scripts/TH1_UI/View/Outside/RoomNameInputValidator.cs
2026-05-27 22:46:45 +08:00

78 lines
2.2 KiB
C#

using TH1_Logic.Chat;
namespace TH1_UI.View.Outside
{
internal static class RoomNameInputValidator
{
public const int MinRoomNameLength = 2;
public const int MaxRoomNameLength = 20;
public const string InvalidRoomNameHint = "房间名称包含不适当内容,请修改后再确认。禁止使用辱骂、歧视、色情、广告、冒充官方或泄露隐私等内容。";
public const string InvalidCharactersHint = "房间名称只能使用中文、英文字母、数字、下划线、中划线和点。";
public enum ErrorType
{
None,
Illegal,
TooShort
}
public static string SanitizeAllowedCharacters(string input)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
var result = new System.Text.StringBuilder();
foreach (char c in input.Trim())
{
bool isChinese = c >= '\u4e00' && c <= '\u9fff';
bool isLetter = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
bool isDigit = c >= '0' && c <= '9';
bool isAllowedSymbol = c == '_' || c == '-' || c == '.';
if (isChinese || isLetter || isDigit || isAllowedSymbol)
{
result.Append(c);
}
if (result.Length >= MaxRoomNameLength) break;
}
return result.ToString();
}
public static bool TryValidateForSubmit(string input, string fallbackRoomName, out string roomName, out string hint)
{
ErrorType errorType;
if (TryValidateForSubmitWithErrorType(input, fallbackRoomName, out roomName, out errorType))
{
hint = null;
return true;
}
hint = errorType == ErrorType.TooShort ? string.Empty : InvalidRoomNameHint;
return false;
}
public static bool TryValidateForSubmitWithErrorType(string input, string fallbackRoomName, out string roomName, out ErrorType errorType)
{
roomName = SanitizeAllowedCharacters(input);
if (string.IsNullOrEmpty(roomName)) roomName = SanitizeAllowedCharacters(fallbackRoomName);
if (roomName.Length < MinRoomNameLength)
{
errorType = ErrorType.TooShort;
return false;
}
var filtered = BannedWordFilter.Filter(roomName, BannedTextContext.Name);
if (filtered != roomName)
{
errorType = ErrorType.Illegal;
return false;
}
errorType = ErrorType.None;
return true;
}
}
}