Checking a value against a pattern
Some values must match a shape rather than a range. A postcode, a reference number and an email address all have a pattern.
A pattern validator
Markup
<asp:TextBox id="txtRef" runat="server" />
<asp:RegularExpressionValidator
ControlToValidate="txtRef"
ValidationExpression="\d{4}\w{2}"
ErrorMessage="Use four digits then two letters"
runat="server" />Reading a pattern
- A backslash letter stands for a class of characters, such as a digit or a word character.
- Curly braces give a count of how many times the previous piece repeats.
- An anchor at each end insists the whole value matches, not just part of it.
Keep patterns simple. A pattern that nobody on the team can read is a maintenance problem. If a rule is complex, consider checking it in code where you can explain it.
Validation sits beside presentation. To control how controls look, read styling server controls with a stylesheet.