1

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 ?

tereško
  • 58,060
  • 25
  • 98
  • 150
user1740381
  • 2,121
  • 8
  • 37
  • 61
  • Can you post your custom validation logic? Usualy this priblem is resolved by keeping the format string in the resource file and then use the string.Format to inject the min and max – Alexandr Mihalciuc Aug 28 '13 at 08:19

1 Answers1

9

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

Community
  • 1
  • 1
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • But how can i use this string.Format within data-annotation, means here `[Required(ErrorMessageResourceName = "PostTitleRequired", ErrorMessageResourceType = typeof(ValidationResource))]` – user1740381 Aug 28 '13 at 08:26
  • @user1740381 Well, Required is certainly not a good example. You can have ValidationAttributes with parameters (see StringLengthAttribute for example). Than you can build your error message with your resource using string.Format. – Raphaël Althaus Aug 28 '13 at 08:30
  • I used like this `[StringLength(5, ErrorMessage = string.Format(ValidationResource.PostTitleLength, 1, 5), ErrorMessageResourceType = typeof(ValidationResource), MinimumLength = 1)]` but getting error – user1740381 Aug 28 '13 at 08:34
  • Just found : http://stackoverflow.com/questions/9540314/modify-default-errormessage-for-stringlength-validation – Raphaël Althaus Aug 28 '13 at 08:38