How do I combine resource strings for validation attribute error messages?

一曲冷凌霜 提交于 2019-12-06 00:02:24

问题


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?


回答1:


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

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."
}


来源:https://stackoverflow.com/questions/22849431/how-do-i-combine-resource-strings-for-validation-attribute-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!