Regular Expression Validator Control Sample

The regular expression validator control shown here extends the base validator control described in the Base Validator Control Sample. This validator adds the following functionality to the base validator:

  • It exposes a property named ValidationExpression that allows a user (page developer) to specify a regular expression.
  • It overrides the EvaluateIsValid method (defined as an abstract method in BaseDomValidator) to provide logic to determine whether the field to validate matches the pattern specified by the regular expression.
  • It overrides AddAttributesToRender (inherited from WebControl) to provide a client-side handler for the evaluation logic. The client-side handler is a function defined in the script library.

To compile and build this sample, see the instructions in Validator Control Samples. For an overview of client-side scripting in server controls, see Client-Side Functionality in a Server Control.

// RegexDomValidator.cs.
namespace DomValidators {

    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Diagnostics;
    using System.Text.RegularExpressions;
    using System.Drawing.Design;
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    ToolboxData("<{0}:RegexDomValidator runat=server ErrorMessage=\"RegexDomValidator\"></{0}:RegexDomValidator>")
    public class RegexDomValidator : BaseDomValidator {

        Editor("System.Web.UI.Design.WebControls.RegexTypeEditor,System.Design", typeof(UITypeEditor)),
        public string ValidationExpression {
            get { 
                object o = ViewState["ValidationExpression"];
                return((o == null) ? String.Empty : (string)o);
            set {
                try {
                    Regex.IsMatch("", value);
                catch (Exception e) {
                    //Throw new HttpException.
                    //                       HttpRuntime.FormatResourceString(SR.Validator_bad_regex, value), e);
                    throw new HttpException("Bad Expression", e);
                ViewState["ValidationExpression"] = value;

        protected override void AddAttributesToRender(HtmlTextWriter writer) {
            if (RenderUplevel) {
                writer.AddAttribute("evaluationfunction", "RegularExpressionValidatorEvaluateIsValid");
                if (ValidationExpression.Length > 0) {
                    writer.AddAttribute("validationexpression", ValidationExpression);

        protected override bool EvaluateIsValid() {

            // Validation always succeeds if input is empty or value was not found.
            string controlValue = GetControlValidationValue(ControlToValidate);
            Debug.Assert(controlValue != null, "Should have already been checked");
            if (controlValue == null || controlValue.Length == 0) {
                return true;

            try {
                // Looking for an exact match, not just a search hit.
                Match m = Regex.Match(controlValue, ValidationExpression);
                return(m.Success && m.Index == 0 && m.Length == controlValue.Length);
            catch {
                Debug.Fail("Regex error should have been caught in property setter.");
                return true;

[VisualĀ Basic]
' RegexDomValidator.vb
Option Explicit
Option Strict

Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Diagnostics
Imports System.Text.RegularExpressions
Imports System.Drawing.Design
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace DomValidators
   <ToolboxData("<{0}:RegexDomValidator runat=server ErrorMessage=""RegexDomValidator""></{0}:RegexDomValidator>")> _
   Public Class RegexDomValidator
      Inherits BaseDomValidator

      <Bindable(True), _
         Category("Behavior"), _
         DefaultValue(""), _
         Editor("System.Web.UI.Design.WebControls.RegexTypeEditor,System.Design", _
         GetType(UITypeEditor)), _
         Description("ValidationExpression")> _
      Public Property ValidationExpression() As String
            Dim o As Object = ViewState("ValidationExpression")
            If o Is Nothing Then
               Return String.Empty
               Return CStr(o)
            End If
         End Get
               Regex.IsMatch("", value)
            Catch e As Exception
               'Throw new HttpException.
               '                       HttpRuntime.FormatResourceString(SR.Validator_bad_regex, value), e);
               Throw New HttpException("Bad Expression", e)
            End Try
            ViewState("ValidationExpression") = value
         End Set
      End Property
      Protected Overrides Sub AddAttributesToRender(writer As HtmlTextWriter)
         If RenderUplevel Then
            writer.AddAttribute("evaluationfunction", "RegularExpressionValidatorEvaluateIsValid")
            If ValidationExpression.Length > 0 Then
               writer.AddAttribute("validationexpression", ValidationExpression)
            End If
         End If
      End Sub
      Protected Overrides Function EvaluateIsValid() As Boolean
         ' Always succeeds if input is empty or value was not found.
         Dim controlValue As String = GetControlValidationValue(ControlToValidate)
         Debug.Assert( Not (controlValue Is Nothing), "Should have already been checked")
         If controlValue Is Nothing Or controlValue.Length = 0 Then
            Return True
         End If
            ' Looking for an exact match, not just a search hit.
            Dim m As Match = Regex.Match(controlValue, ValidationExpression)
            Return m.Success And m.Index = 0 And m.Length = controlValue.Length
         End Try
      End Function
   End Class
End Namespace

See Also

Validator Control Samples | Base Validator Control Sample | Required Field Validator Control Sample | Script Library for Validator Sample | Configuration File for Validator Sample | Test Page for Validator Sample | Developing a Validator Control