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; }