使用数据注释验证获取非法字符

Get illegal characters with data annotations validation

我正在使用数据注释来检测网页文本框中的非法字符。

[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);

如果检测到任何非法字符,结果将有一个带有"Full name is invalid."

的错误字符串

如何获取在字段中输入的非法字符列表?字符串 inputFieldValue 将包含用户在字段中键入的内容。如何使用 @"^[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();