ASP.NET RegularExpressionValidator Examples: What It Checks, Where It Fails, and When to Use Something Else

Practical RegularExpressionValidator examples for ASP.NET Web Forms, plus client/server regex differences, Unicode pitfalls, empty-input behavior and accessibility notes.

RegularExpressionValidator is an ASP.NET Web Forms validation control that checks whether the value of an input control, usually a TextBox, matches a pattern. This review walks through working examples and explains the parts of its behavior that most often surprise developers: empty input, differences between the browser and server checks, and how Unicode text interacts with common patterns.

Is RegularExpressionValidator the right tool?

It is a good fit for simple format checks on single fields in a Web Forms page: postal codes, numeric IDs, fixed-format reference numbers and basic length limits. The main benefit is that one declarative setting produces both an immediate in-browser check and a server-side check. The decisive tradeoff is that the same pattern is evaluated by two different regex engines, JavaScript in the browser and .NET on the server, so any construct the two handle differently can produce inconsistent results.

A plainer approach is preferable when the field holds people's names, addresses or other free text, when users may type in many languages, when the rule needs logic a pattern expresses poorly (date ranges, checksums, cross-field comparisons), or when input should be trimmed or normalized before it is judged. In those cases, accept the text broadly and validate in server code, for example with a CustomValidator. If you are not using Web Forms, this control does not apply; in MVC and ASP.NET Core the comparable mechanism is the RegularExpression data annotation attribute.

What the validator actually changes

Nothing in the text itself. The validator does not trim, normalize, reverse, mirror or restyle the value; it only reports whether the value is valid and shows or hides an error message. "Regular expression" here means pattern matching, not a text transformation, so readers looking for reversed or mirrored text tools are in the wrong place.

The match must cover the whole value. The control accepts input only when the pattern matches starting at the first character and ending at the last, so the anchors ^ and $ are not required (adding them is harmless). For example, the pattern [0-9]{5} rejects 123456 even though five of its digits match.

Empty input passes. If the field is blank, or contains only whitespace, the validator treats it as valid and does not evaluate the pattern. To make a field mandatory, pair it with a RequiredFieldValidator on the same control.

The browser check is a convenience, not a safeguard. Client script can be disabled or bypassed, so server code must check Page.IsValid before using the value.

Basic markup example

<asp:TextBox ID="ZipCode" runat="server" />
<asp:RequiredFieldValidator ID="ZipRequired" runat="server"
    ControlToValidate="ZipCode"
    ErrorMessage="Enter a ZIP code."
    Display="Dynamic" />
<asp:RegularExpressionValidator ID="ZipFormat" runat="server"
    ControlToValidate="ZipCode"
    ValidationExpression="[0-9]{5}(-[0-9]{4})?"
    ErrorMessage="Enter a 5-digit ZIP code, or ZIP+4 such as 12345-6789."
    Display="Dynamic"
    SetFocusOnError="true" />
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
protected void Submit_Click(object sender, EventArgs e)
{
    if (!Page.IsValid)
    {
        return;
    }

    // Safe to use ZipCode.Text here.
}

Common pattern examples

Purpose | ValidationExpression | Notes
US ZIP code or ZIP+4 | [0-9]{5}(-[0-9]{4})? | Uses [0-9] rather than \d for consistent client and server results
Whole number | [0-9]+ | No sign, no separators
Decimal with up to two places | [0-9]+(.[0-9]{1,2})? | Requires at least one digit before the point
US phone number, loose | (?[0-9]{3})?[-. ]?[0-9]{3}[-. ]?[0-9]{4} | Also accepts unbalanced parentheses such as (555 123-4567
Email, plausibility only | [^@\s]+@[^@\s]+.[^@\s]+ | Does not prove the address exists; confirm by sending a message
Maximum length including line breaks | [\s\S]{0,500} | Counts UTF-16 code units, not visible characters (see below)
Password with digit, lowercase and uppercase | (?=.[0-9])(?=.[a-z])(?=.*[A-Z]).{8,} | Lookahead works in both engines; ASCII letters only

Where the browser and server checks disagree

  • \d and \w: in .NET these match Unicode digits and word characters, such as Arabic-Indic digits; in JavaScript they match ASCII only. A value can fail in the browser yet pass on the server if client script is bypassed. Use [0-9] and explicit character ranges when you mean ASCII.
  • Inline options: a leading (?i) is .NET syntax and is not accepted as a global flag in browser JavaScript. Spell out both cases instead, for example [A-Za-z].
  • Unicode categories: .NET supports \p{L} and similar classes. The standard client script builds the expression without the JavaScript Unicode flag, so in the browser \p{L} is not treated as a letter category.
  • .NET-only constructs: atomic groups, balancing groups and some other .NET features have no JavaScript equivalent, and lookbehind is missing from some older browsers.
  • If a pattern genuinely needs .NET features, set EnableClientScript="false" so only the server evaluates it, and accept the loss of instant feedback.

Unicode input: what the pattern actually sees

Both engines operate on UTF-16 code units, not on characters as a reader perceives them. An emoji outside the Basic Multilingual Plane is two code units; emoji with skin-tone modifiers or joiner sequences are more. A letter written as a base letter plus a combining accent, such as e followed by a combining acute mark, is two code units, while the precomposed é is one. A length pattern like [\s\S]{0,20} can therefore reject text that looks shorter than 20 characters, and the validator performs no normalization to make the two spellings of é behave the same.

Stylized "fancy font" text, such as bold or script letters copied from Unicode styling generators, consists of separate code points rather than formatting. These letters fail ASCII ranges like [A-Za-z], and because each one is stored as a surrogate pair, .NET's \p{L} also fails to match them: each half of the pair is a surrogate, not a letter. Right-to-left text such as Hebrew or Arabic is matched in its stored logical order, not in the order it appears on screen.

If a field must accept international names or arbitrary text, restrictive patterns will reject legitimate input. Either avoid pattern-based validation for that field, or validate on the server with a CustomValidator that normalizes the string (for example to Unicode Normalization Form C) before checking it.

Copying, pasting and accessibility

Because the validator leaves the value unchanged, it has no effect on how the entered text copies or displays elsewhere. Pasting into the field is the more common problem: pasted values often carry leading or trailing spaces or non-breaking spaces, and the validator does not trim them, so [0-9]{5} rejects " 12345". Either allow optional whitespace at both ends with \s* and trim in server code, or tell users which format is expected.

The error message is what users actually read. Display="Static" reserves space for the message, Display="Dynamic" adds it to the layout only when shown, and Display="None" suppresses inline display, typically when a ValidationSummary lists errors instead. ErrorMessage feeds the summary, and Text, if set, replaces it inline. SetFocusOnError moves focus to the failing field.

Write messages that describe the expected format in plain language, such as "Enter a 5-digit ZIP code, for example 12345", rather than repeating the regex. Put format guidance in the visible label or hint text too, so users know the rule before they submit. Whether a screen reader announces the message when it appears depends on the rendered markup, the browser and the assistive technology. This review includes no test with any specific screen reader, so verify the behavior with the tools your users rely on.

Testing a pattern before shipping

  • Test in both flavors: many online regex testers default to a single engine, so run the pattern under JavaScript and .NET settings.
  • Cover valid examples and exact boundary lengths.
  • Try empty input, whitespace-only input, and leading or trailing spaces.
  • Try non-ASCII digits, accented letters in both precomposed and decomposed form, emoji, and stylized Unicode letters.
  • Paste from a word processor to catch smart quotes and non-breaking spaces.
  • Submit once with client script enabled and once with it disabled to exercise the server path.
  • Avoid nested quantifiers such as (a+)+, which can cause catastrophic backtracking on crafted input, and check your framework documentation for a match timeout setting on the control.

Setup note for .NET Framework 4.5 and later

When a site targets .NET Framework 4.5 or later, unobtrusive validation is enabled by default and requires a script resource mapping named jquery. Without that mapping, pages that use validators throw an error at runtime. Either register the mapping, or turn unobtrusive validation off in web.config:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Limits of this review

No product-specific measurements, version timelines or test results were available for this article. The behavior described is the control's documented design together with general properties of the .NET and JavaScript regex engines. Browser-specific rendering and screen reader announcements were not tested and should be verified in your own target environments.