I was using attributes from the System.ComponentModel.DataAnnotations namespace for model validation. This namespace includes a few very useful validation attributes such as
- Required Attribute – Validates the field has a value
- Range Attribute – Validates the field is within a given range
- RegularExpression Attribute – Validates the field matches a given regular expression.
The regular expression attribute is very useful since you can describe exactly what format you want a string property to be in. While using this though I ran into a problem. The attribute doesn’t let you specify RegexOptions. This was an issue for me since I wanted to use the regex to validate that the users input was between 5 and 200 characters long , so I had attribute that property as such:
[RegularExpression(@".{5,200}")] public string Text{get;set;}
However this doesn’t work since by default the wildcard . does not match new lines (which I am allowing in the input). The way to fix this is to specify the RegexOptions.SingleLine option to either the Regex constructor or Match function. The problem is I have no way of doing that here, and there is no argument on the attribute constructor to specify those options. I was considering overriding the attribute to create one that allows specifying the attribute but then I stumbled upon this:
You are able to specify the regex option inside of the regular expression text! (which I thought was a huge discovery until my co-worker said he knew this all along but never let me know!).
So I just changed the expression to look like this:
[RegularExpression(@"(?s).{5,200}")] public string Text{get; set;}
The (?s) is the inline regex option definition so say I want this in SingleLine mode! And now the validation works the way I wanted!