Matt Purdy
Feb 11, 2021
(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

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


Please login to comment.
Latest blogs
Plug-in manager is back in CMS 12

Plug-in manager is back in the UI, what is it and how can i use it?

Luc Gosso (MVP) | Oct 6, 2022 | Syndicated blog

Display Child Pages in Content Delivery API Response

The below example will implement an instance of IContentConverterProvider to customise the serialisation of PageData and output child pages in the...

Minesh Shah (Netcel) | Oct 4, 2022

Bring the Report Center back in Optimizely CMS 12

The Report Center has been a part of Optimizely CMS since its first debut in version 5R2 in 2008, but in CMS 12, it's removed! Don't despair! Make...

Tomas Hensrud Gulla | Oct 4, 2022 | Syndicated blog

Customizing Property Lists in Optimizely CMS

Generic property lists is a cool editorial feature that has gained a lot of popularity - in spite of still being unsupported (officially). But if y...

Allan Thraen | Oct 2, 2022 | Syndicated blog