November Happy Hour will be moved to Thursday December 5th.

Matt Purdy
Feb 11, 2021
  2281
(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 SaaS CMS + Coveo Search Page

Short on time but need a listing feature with filters, pagination, and sorting? Create a fully functional Coveo-powered search page driven by data...

Damian Smutek | Nov 21, 2024 | Syndicated blog

Optimizely SaaS CMS DAM Picker (Interim)

Simplify your Optimizely SaaS CMS workflow with the Interim DAM Picker Chrome extension. Seamlessly integrate your DAM system, streamlining asset...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Optimizely CMS Roadmap

Explore Optimizely CMS's latest roadmap, packed with developer-focused updates. From SaaS speed to Visual Builder enhancements, developer tooling...

Andy Blyth | Nov 21, 2024 | Syndicated blog

Set Default Culture in Optimizely CMS 12

Take control over culture-specific operations like date and time formatting.

Tomas Hensrud Gulla | Nov 15, 2024 | Syndicated blog

I'm running Optimizely CMS on .NET 9!

It works 🎉

Tomas Hensrud Gulla | Nov 12, 2024 | Syndicated blog

Recraft's image generation with AI-Assistant for Optimizely

Recraft V3 model is outperforming all other models in the image generation space and we are happy to share: Recraft's new model is now available fo...

Luc Gosso (MVP) | Nov 8, 2024 | Syndicated blog