C# 通过数据批注验证获取非法字符
我正在使用数据注释检测网页文本框中的非法字符C# 通过数据批注验证获取非法字符,c#,regex,validation,data-annotations,C#,Regex,Validation,Data Annotations,我正在使用数据注释检测网页文本框中的非法字符 [RegularExpression(Constants.LegalName, ErrorMessage = "Full name is invalid.")] public string FullName { get; set; } const string LegalName= @"^[a-zA-Z '-.]*$"; 我用以下代码验证字段 Validator.TryValidateObject( inputFieldV
[RegularExpression(Constants.LegalName, ErrorMessage = "Full name is invalid.")]
public string FullName {
get;
set;
}
const string LegalName= @"^[a-zA-Z '-.]*$";
我用以下代码验证字段
Validator.TryValidateObject(
inputFieldValue,
new ValidationContext(inputFieldValue, null, null),
result,
true);
如果检测到任何非法字符,结果将有一个错误字符串“全名无效”
如何在字段中输入非法字符列表?字符串inputFieldValue将具有用户在字段中键入的内容。如何使用reg express获取所有非法字符的列表,如@“^[a-zA-Z'-.]*$”代码>
谢谢。我不确定您是否可以使用TryValidateObject
获得它。您必须分别找到它们:
const string ValidCharPattern = @"[a-zA-Z '-.]";
const string LegalName= @"^" + ValidCharPattern + @"*$";
var invalidChars = Regex
.Replace(
input: inputFieldValue,
pattern: ValidCharPattern,
replacement: String.Empty)
.Distinct();
为什么不在消息中提及哪些字符是有效的,而不是尝试在消息中查找并放置无效字符?