2017-01-19 46 views
0

我正在使用數據註釋來檢測網頁文本框中的非法字符。使用數據註釋驗證獲取非法字符

[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將具有用戶在該字段中鍵入的內容。我怎麼能得到所有非法字符列表像@"^[a-zA-Z '-.]*$";

謝謝。

+0

爲什麼不提及消息中的哪些字符是有效的,而不是試圖在消息中找到並放置無效字符? – juharr

回答

0

我不確定你可以用TryValidateObject得到它。你必須單獨找到它們:

const string ValidCharPattern = @"[a-zA-Z '-.]"; 

const string LegalName= @"^" + ValidCharPattern + @"*$"; 


var invalidChars = Regex 
    .Replace(
     input: inputFieldValue, 
     pattern: ValidCharPattern, 
     replacement: String.Empty) 
    .Distinct();