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

Try our conversational search powered by Generative AI!

Linus Ekström
Dec 4, 2013
  6738
(2 votes)

Email validation attribute and support for IMetadataAware

In this blog post I will describe one new feature in EPiServer 7.5 as well as another feature that was actually removed in a last minute change (as well as describing how you can implement this yourself). The feature that was removed was an EPiServer attribute called EmailAttribute that could be applied to a string property to enable email validation. In code it would look like this:

[Email]
public virtual string Email { get; set; }

 

The reason for us to remove this was that there actually exists such a attribute in the System.ComponentModel.DataAnnotations namespace in .NET 4.5 (well, actually it’s called EmailAddressAttribute so there was a slight naming difference). So to avoid confision, we have removed our attribute. Using the .NET attribute should work with the limitation that the validation will be done server side since we have not added logic to send settings to the client yet. If you want to use an attribute that has support for client side validation as well as the ability to add several comma-separated email addresses you can add your own attribute with the following code:

using System;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using EPiServer.Framework.Localization;
 
namespace Samples
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class EmailAttribute : ValidationAttribute, IMetadataAware
    {
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            var extendedMetadata = metadata as ExtendedMetadata;
 
            if (extendedMetadata == null)
            {
                return;
            }
 
            string emailRegexPattern = AllowMultiple ? Framework.Validator.MultipleEmailRegexString : Framework.Validator.EmailRegexString;
 
            extendedMetadata.EditorConfiguration["pattern"] = emailRegexPattern;
            extendedMetadata.EditorConfiguration["invalidMessage"] = LocalizationService.Current.GetString("/episerver/shell/ui/resources/JQueryValidate/email");
        }
 
        public override string FormatErrorMessage(string name)
        {
 
            return LocalizationService.Current.GetString("/episerver/shell/ui/resources/JQueryValidate/email");
        }
 
        public override bool IsValid(object value)
        {
            var stringValue = value as string;
            if (String.IsNullOrEmpty(stringValue))
            {
                return true;
            }
 
            if (AllowMultiple)
            {
                return Framework.Validator.MultipleEmailRegex.IsMatch(stringValue);
            }
            else
            {
                return Framework.Validator.EmailRegex.IsMatch(stringValue);
            }
        }
 
        public bool AllowMultiple { get; set; }
    }
}

IMetadataAware

If you take a look at the class above, the class inherrits from ValidationAttribute and there are two methods that are overridden to implement server side validation: IsValid and FormatErrorMessage. This was possible in the EPiServer 7 release so nothing new here. What’s new, however, is the support in EPiServer for the IMetadataAware interface (from System.Web.Mvc). I’m very excited about this since it makes it possible to add attributes that can handle both client and server side validation in one class which should bring on possibilities to add lots of cool validation attributes. In the class above, we define the “pattern” setting which is used by the standard text editor to validate input against a regular expression.

Note that the class above is using a translation from the EPiServer resources files directly. This is not part of our supported API and might change without notice over time…

Dec 04, 2013

Comments

Petter Klang
Petter Klang Dec 19, 2013 12:03 PM

Thanks for sharing this. Will surely come in handy

Please login to comment.
Latest blogs
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

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