RegularExpression 屬性
該 [RegularExpression]
屬性可以裝飾任何屬性或公共欄位,並指定必須為屬性值相匹配的正規表示式被視為有效。
[RegularExpression(validationExpression)]
public string Property { get; set; }
此外,它接受一個可選的 ErrorMessage
屬性,可用於設定輸入無效資料時使用者收到的訊息:
[RegularExpression(validationExpression, ErrorMessage = "{your-error-message}")]
public string Property { get; set; }
例子)
[RegularExpression(@"^[a-z]{8,16}?$", ErrorMessage = "A User Name must consist of 8-16 lowercase letters")]
public string UserName{ get; set; }
[RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Please enter a valid ZIP Code (e.g. 12345, 12345-1234)")]
public string ZipCode { get; set; }