Posts tagged with: dataannotations

Making custom dataannotation attributes work with MVC client side validation

In a previous blog entry I showed you a easier approach to localized DataAnnotation attributes.

The problem with that approach was that client side validation didn’t work. It isn’t hard to fix. All you need is to borrow some code from the built in DataAnnotation support and reference the custom attributes instead.

Here is a sample implementation.

    public class RequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute>
    {
        public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
        }

        public static void SelfRegister()
        {
            DataAnnotationsModelValidatorProvider
                .RegisterAdapter(
                    typeof (RequiredAttribute),
                    typeof (RequiredAttributeAdapter));
        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            return new[] { new ModelClientValidationRequiredRule(ErrorMessage) };
        }
    }

Then simply call RequiredAttributeAdapter.SelfRegister(); somewhere in your Global.asax


Simplified localization for DataAnnotations

Update

I’ve come up with a better localization method for MVC3. Read about it here.

Original article

The built in localization support in DataAnnotations is a bit hard to work with. You are supposed to do add the ResourceManager to each attribute that you add. The code is looking like something like this:

    public class User
    {
        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        public int Id { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        public string LastName { get; set; }
    }

You should of course move the strings to a static class or something like that.

The problem is that you have just added translation for the validation messages and not the actual model. There are actually no built in solutions for that problem.. If you google, you find some solutions using a custom LocalizedDisplayNameAttribute that uses the same approach as the DataAnnotationAttribute’s: Pointing on a resource type in the attribute constructor.

Updated source code for this solution:

    public class User
    {
        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_Id", NameResourceType=typeof(ModelTranslations))]
        public int Id { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_FirstName", NameResourceType=typeof(ModelTranslations))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(ModelTranslations))]
        [StringLength(40, ErrorMessageResourceName = "Validation_StringLength", ErrorMessageResourceType = typeof(ModelTranslations))]
        [LocalizedDisplayNameAttribute("User_LastName", NameResourceType=typeof(ModelTranslations))]
        public string LastName { get; set; }
    }

Not very readable, is it? As you can see, I use the pattern ClassName_PropertyName for all strings definitions. It’s a safe way to avoid a name collision. The same word might not mean the same thing in different models.

The solution

What we need is a way to provide strings to all attributes WITHOUT specifying the resource in the attribute constructors. In this way we can easily move resources without having to change each attribute. Changing every attribute is not very DRY is it?

My solution is to create a singleton class that you can fetch strings from. Want a more flexible solution? Check my ShureValidation library (shameless advertising) that I’ve posted about earlier in this blog.

End result for the model:

    public class User
    {
        [Required]
        [LocalizedDisplayNameAttribute("User_Id")]
        public int Id { get; set; }

        [Required]
        [StringLength(40)]
        [LocalizedDisplayNameAttribute("User_FirstName")]
        public string FirstName { get; set; }

        [Required]
        [StringLength(40)]
        [LocalizedDisplayNameAttribute("User_LastName")]
        public string LastName { get; set; }
    }

A bit more readable? oooooh yes *uhu*.

Classes making it possible:

You have to derive all standard DataAnnotation attribute classes like this:

    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
    {
        private string _displayName;

        public RequiredAttribute() 
        {
            ErrorMessageResourceName = "Validation_Required";
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            _displayName = validationContext.DisplayName;
            return base.IsValid(value, validationContext);
        }

        public override string FormatErrorMessage(string name)
        {
            var msg = LanguageService.Instance.Translate(ErrorMessageResourceName);
            return string.Format(msg, _displayName);
        }
    }

Next step is to add a custom DisplayName class:

    public class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        private PropertyInfo _nameProperty;
        private Type _resourceType;

        public LocalizedDisplayNameAttribute(string className, string propertyName)
            : base(className + (propertyName == null ? "_Class" : ("_" + propertyName)))
        {

        }

        public override string DisplayName
        {
            get
            {
                return LanguageService.Instance.Translate(base.DisplayName) ?? "**" + base.DisplayName + "**";
            }
        }
    }

And finally create the language service:

    public class LanguageService
    {
        private static LanguageService _instance = new LanguageService();
        private List<ResourceManager> _resourceManagers = new List<ResourceManager>();

        private LanguageService()
        {
        }

        public static LanguageService Instance { get { return _instance; } }

        public void Add(ResourceManager mgr)
        {
            _resourceManagers.Add(mgr);
        }

        public string Translate(string key)
        {
            foreach (var item in _resourceManagers)
            {
                var value = item.GetString(key);
                if (value != null)
                    return value;
            }

            return null;
        }
    }

You can easily switch to a database or something like that if you need to.

Update

A follow up entry showing how to fix client-side validation in MVC3 can be found here.