1

So I can create a property like so:

    [StringLength(250, ErrorMessage = "Please limit your {0} to {1} characters")]
    [DisplayName("Project name")]
    public string Name { get; set; }

And if the length entered is longer than 250 characters, it will display the following error:

Please limit your Project name to 250 characters

Is there a way to make the {0} appear as lower case so that the message is like:

Please limit your project name to 250 characters

Pete
  • 57,112
  • 28
  • 117
  • 166
  • Where are {0} and {1} being filled in? – Alfie Goodacre Oct 27 '16 at 15:02
  • 1
    Pretty sure it's bound to the same rules as `string.format`, so no method to do that from what I understand. Perhaps there is a way to create a custom validator where you can apply your own formatting code logic. But not really sure what to search to find if that's an option – musefan Oct 27 '16 at 15:06
  • 1
    Well, this may sound silly, but you are already hard-coding the label in the DisplayName attribute. Why not just hard-code it in the StringLength attribute too? :-) – JuanR Oct 27 '16 at 15:09
  • @AlfieGoodacre I'm guessing MVC does it behind the scenes when it converts the data annotations – Pete Oct 27 '16 at 15:19
  • @Juan good point I guess I could do that but then the point of using the string replacement things is that you would only need to change the name or length in one place - there have been plenty of times where a developer has changed the display name or string length and then forgotten to change the hard coded values (which is why we moved to this way of doing things). Also not sure if you are able to do this, but if you had something that was inheriting from this that changed the display name - would that not affect the error message - you may end up with a load of hardcoded errors all over – Pete Oct 27 '16 at 15:21
  • Possible duplicate of [C# string format flag or modifier to lowercase param](http://stackoverflow.com/questions/1839649/c-sharp-string-format-flag-or-modifier-to-lowercase-param) – Pete Oct 27 '16 at 15:34
  • Looks like I have to wait for c# 5.0 where I can do something like `{0:L}` – Pete Oct 27 '16 at 15:35
  • U can see this http://stackoverflow.com/questions/3557953/how-to-put-displayname-on-errormessage-format – aguetat Oct 27 '16 at 15:48

0 Answers0