Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

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.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.