moath naji
moath naji

Reputation: 661

create generic messages for c# Mvc Validation

i need to simply store the generic validation messages for Compatibility i have tried something like this

public static class GemericMessages
    {
        public static readonly string Required = "Required Filed";
    }

[Required(ErrorMessage = GemericMessages.Required)]
        public string UserName { get; set; }

but i'am facing error say's : "An attribute argument must be a constant expression, typeof expression or array creation expression"

what are the best practice to done this , and how to fix this error please ?

Upvotes: 0

Views: 248

Answers (2)

vendettamit
vendettamit

Reputation: 14677

You an use resource string instead. An overload of Required field attribute allows you to pass in resource class and respective fieldName.

[Required(ErrorMessageResourceType = typeof(Resource1), ErrorMessageResourceName = "requiredField")]

To add a resource file if it's not already exists in your project simply right click on your project. Add new item and select resource file. After adding it in the project you can double click to open it and enter your string for validation message:

enter image description here

Upvotes: 1

Connor Hull
Connor Hull

Reputation: 11

Vendettamit's answer is correct, but if you don't wish to use resources for some reason, it will work to mark your string const instead of readonly.

public const string Required = "Required Filed";

Upvotes: 1

Related Questions