How to combine resource strings for validation attribute error messages?

If I had error messages in the validation attribute, for example:

  • Name required
  • Last name required

and then the validation attribute as follows:

[Required(ErrorMessageResourceName = "Error_FirstNameRequired", ErrorMessageResourceType = typeof(Strings)] public string FirstName {get;set;} 

I do not want a translation to be made for each instance of this. Is there a way to combine resource strings in formatting, for example:

 [Required(ErrorMessage = string.Format("{0} {1}", Strings.Label_FirstName, Strings.Error_IsRequired))] public string FirstName {get;set;} 

Of course, this does not work, because it must be a compile-time constant. But is it possible to achieve this so that I can build localized strings and reuse those that already exist? I was thinking of creating custom attributes that allow you to set additional properties and override the default message displayed, but it will be too much refactoring and some kind of kludgy imo.

Any ideas?

+6
source share
1 answer

You can use formatting in the strings defined in your resources. When you use {0} , as shown in FieldRequired , the display name will be inserted when possible. Otherwise, it will return to the property name, as shown for MiddleName .

Example:

Resources:

Strings.resx
String.resx

Strings.nl.resx
Strings.nl.resx

Implementation:

 public class MyClass { [Display(ResourceType = typeof(Strings), Name = "FirstName")] [Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Strings))] public string FirstName { get; set; } [Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Strings))] public string MiddleName { get; set; } [Display(ResourceType = typeof(Strings), Name = "LastName")] [Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(Strings))] public string LastName { get; set; } // Validation errors for culture [en] would be: // "First name is a required field." // "MiddleName is a required field." // "Last name is a required field." // // Validation errors for culture [nl] would be: // "Voornaam is een benodigd veld." // "MiddleName is een benodigd veld." // "Achternaam is een benodigd veld." } 
+14
source

All Articles