SaaS CMS has officially launched! Learn more now.

Matt Purdy
Feb 11, 2021
  2023
(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 release SaaS CMS

Discover the future of content management with Optimizely SaaS CMS. Enjoy seamless updates, reduced costs, and enhanced flexibility for developers...

Andy Blyth | Jul 17, 2024 | Syndicated blog

A day in the life of an Optimizely Developer - London Meetup 2024

Hello and welcome to another instalment of A Day In The Life Of An Optimizely Developer. Last night (11th July 2024) I was excited to have attended...

Graham Carr | Jul 16, 2024

Creating Custom Actors for Optimizely Forms

Optimizely Forms is a powerful tool for creating web forms for various purposes such as registrations, job applications, surveys, etc. By default,...

Nahid | Jul 16, 2024

Optimizely SaaS CMS Concepts and Terminologies

Whether you're a new user of Optimizely CMS or a veteran who have been through the evolution of it, the SaaS CMS is bringing some new concepts and...

Patrick Lam | Jul 15, 2024

How to have a link plugin with extra link id attribute in TinyMce

Introduce Optimizely CMS Editing is using TinyMce for editing rich-text content. We need to use this control a lot in CMS site for kind of WYSWYG...

Binh Nguyen Thi | Jul 13, 2024

Create your first demo site with Optimizely SaaS/Visual Builder

Hello everyone, We are very excited about the launch of our SaaS CMS and the new Visual Builder that comes with it. Since it is the first time you'...

Patrick Lam | Jul 11, 2024