Try our conversational search powered by Generative AI!

Matt Purdy
Feb 11, 2021
  1853
(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 and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog

Azure AI Language – Abstractive Summarisation in Optimizely CMS

In this article, I show how the abstraction summarisation feature provided by the Azure AI Language platform, can be used within Optimizely CMS to...

Anil Patel | Apr 18, 2024 | Syndicated blog

Fix your Search & Navigation (Find) indexing job, please

Once upon a time, a colleague asked me to look into a customer database with weird spikes in database log usage. (You might start to wonder why I a...

Quan Mai | Apr 17, 2024 | Syndicated blog