user1740381
user1740381

Reputation: 2199

C# using resource file for validation messages

I am working on an asp.net MVC-4 project. I am using resource file (.resx) for internationalization. I am using it first time so this question may be silly so sorry for that.

I have create a resource file for validation. I have created some custom validation also in my project. One of my custom validation is checking the array item length againt max and min value. So if validation fail than i have to show the validation message something like :

Array length must to less that 5 and greater than 1

Now i do not want to hard code the min (1) and max (5) value in message. So can anyone please tell me how can i achieve this while using resource file to serve validation messages ?

Upvotes: 3

Views: 8521

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Well you can store your messages in resx like that (formatted string)

Array length must to less that {0} and greater than {1}

Then when you use it, something like that

string.Format(resource.GetString("<MyMessage>"), 5, 1);

EDIT

If you wanna use StringLength Attribute, you can do it this way

Resource string could be :

Property {0} : Array length must be less than {1} and greater than {2}

and attribute definition

[StringLength(5, ErrorMessageResourceName = "PostTitleLength"/*or a constant*/, ErrorMessageResourceType = typeof(ValidationResource), MinimumLength = 1)]

or you can inherit from StringLengthAttribute if your error message is always the same.

See Modify default ErrorMessage for StringLength validation

Upvotes: 11

Related Questions