RegularExpression Attribute


The [RegularExpression] attribute can decorate any properties or public fields and specifies a regular expression that must be matched for the property be considered valid.

public string Property { get; set; }

Additionally, it accepts an optional ErrorMessage property that can be used to set the message received by the user when invalid data is entered :

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