Don't miss out Virtual Happy Hour today (April 26).

Try our conversational search powered by Generative AI!

Matt Purdy
Feb 11, 2021
  1868
(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
Azure AI Language – Extractive Summarisation in Optimizely CMS

In this article, I demonstrate how extractive summarisation, provided by the Azure AI Language platform, can be leveraged to produce a set of summa...

Anil Patel | Apr 26, 2024 | Syndicated blog

Optimizely Unit Testing Using CmsContentScaffolding Package

Introduction Unit tests shouldn't be created just for business logic, but also for the content and rules defined for content creation (available...

MilosR | Apr 26, 2024

Solving the mystery of high memory usage

Sometimes, my work is easy, the problem could be resolved with one look (when I’m lucky enough to look at where it needs to be looked, just like th...

Quan Mai | Apr 22, 2024 | Syndicated blog

Search & Navigation reporting improvements

From version 16.1.0 there are some updates on the statistics pages: Add pagination to search phrase list Allows choosing a custom date range to get...

Phong | Apr 22, 2024