Matt Purdy
Feb 11, 2021
  4016
(2 votes)

The versatility of using Regex in custom validation attributes.

Hello there,

To kick of my Episerver blogging activities I have decided to begin with the insight of a powerful combination that can be used to perform strict strongly typed server-side validation.


This example showcases the power of Regex to perform required phone number field validation, which, in this instance was all numeric except for specific characters reserved for area codes.


After creating a validation Regex pattern object, you then use the Regex isMatch method to validate your field data, thus getting your result.

Validation Attribute

public class PhoneNumberValidationAttribute : ValidationAttribute
    {
        private readonly int _charLength;

        public PhoneNumberValidationAttribute(int charLength)
        {
            this._charLength = charLength;
        }

        public override bool IsValid(object value)
        {
            var inputtedVal = value as string;

            var validator = new Regex(@"^[0123456789()+-]+$");

            var isValidInput = inputtedVal != null && (validator.IsMatch(inputtedVal) && inputtedVal.Length <= _charLength);

            return isValidInput;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var result = base.IsValid(value, validationContext);

            if (!string.IsNullOrWhiteSpace(result?.ErrorMessage))
                result.ErrorMessage = $"Phone number must contain only numbers with the exception of the area code.";

            return result;
        }

Further improvements would be more complex pattern matching or enhanced error message overloading.

Model property decoration

[PhoneNumberValidation(30)]
public virtual string TelephoneNumber { get; set; }

Whilst writing this post I came to learn of certain alternative data type attributes available within .NET (System.ComponentModel.DataAnnotations) that would fit most use cases. However, this approach is a still a desirable one when chasing a certain level of autonomy.

Feb 11, 2021

Comments

Please login to comment.
Latest blogs
Optimizely migration from CMS 12 to CMS 13

Upgrading from Optimizely CMS 12 to CMS 13 alongside moving the runtime from .NET 8.0 to .NET 10.0 is far more than a routine version upgrade. It i...

Sanjay Kumar | Apr 24, 2026

Optimizely CMS 13 host(s) management

One of the features I found most impressive is the way Optimizely CMS 13 handles hosts with clear definition and intent. It may sound low level...

Harish Yadav | Apr 23, 2026

Building Opal tools on Optimizely Connect Platform: a Mailchimp walkthrough

About the Mailchimp Opal Tool The  Mailchimp Opal Tool  is an Optimizely Connect Platform app that brings Mailchimp audience operations directly in...

Sanjay Kumar | Apr 22, 2026