Question

If I were to have error messages on a validation attribute like:

  • First Name is required
  • Last Name is required

and then a validation attribute like this:

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

I don't want to have a translation done for every instance of this. Is there a way to combine resource strings in a formatter, for example:

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

Of course this doesn't work because it needs to be a compile time constant. But is there away to achieve this so that I can build localized strings and reuse those that already exist? I thought of just creating custom attributes that allow for extra properties to be set and override the default output message, but that would be way too much refactoring and kind of kludgy imo.

Any ideas?

Was it helpful?

Solution

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 fall back 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."
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top