7

When using Data Annotations Validation, everything works fine until I try to use resources.

Here's the error I get: The name 'ErrorMessageResourceType' does not exist in the current context.

And the code I used:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Microsoft.Web.Mvc;

namespace Project.Models  
{  
    [MetadataType(typeof(LanguageMetaData))]
    public partial class Language
    {
    }

    public class LanguageMetaData
    {
        [Required(ErrorMessageResourceType(typeof(Resources.Errors)), 
                  ErrorMessageResourceName = "IdRequired")]
        public object Id { get; set; }

        [Required(ErrorMessageResourceType(typeof(Resources.Errors)), 
                  ErrorMessageResourceName = "NameRequired")]
        public object Name { get; set; }

        public object Flag { get; set; }
        public object IsDefault { get; set; }
    }
}

I can't find anything wrong with this. Can someone more experienced help me with what's wrong?

Thank you!

3 Answers 3

19

It has to be

ErrorMessageResourceType = typeof(Resources.Errors)

instead of

ErrorMessageResourceType(typeof(Resources.Errors))

This was a small big damn stupid mistake :D

Hope this helps anyone who had the same problem!

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use both ErrorMessageResourceType and ErrorMessageResourceName.

[EmailAddress(ErrorMessageResourceType = typeof(Resource),ErrorMessageResourceName = "Message_ValidEmail")]

Comments

1

Using nameof instead of string is a better option with ErrorMessageResourceName .

This is an example:

[StringLength(maximumLength: 60, MinimumLength = 2, ErrorMessageResourceType = typeof(Resources.Register), ErrorMessageResourceName = nameof(Resources.Register.ChooseRole))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.