C# 自定义字段名校验 - 字节长度、首字母、字符限制
可以使用以下代码来验证自定义字段名:
public static bool ValidateFieldName(string fieldName)
{
if (string.IsNullOrEmpty(fieldName))
return false;
if (fieldName.Length > 20)
return false;
if (!char.IsLetter(fieldName[0]) && fieldName[0] != '_')
return false;
foreach (char c in fieldName)
{
if (!char.IsLetterOrDigit(c) && c != '_' && !IsChinese(c))
return false;
}
return true;
}
public static bool IsChinese(char c)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
return uc == UnicodeCategory.OtherLetter || uc == UnicodeCategory.OtherPunctuation;
}
这段代码使用了 char.IsLetter、char.IsDigit 和 CharUnicodeInfo.GetUnicodeCategory 方法来判断字段名中的字符类型,从而判断是否符合要求。其中 IsChinese 方法用来判断是否为汉字。
原文地址: https://www.cveoy.top/t/topic/luFX 著作权归作者所有。请勿转载和采集!