string.Format in Data Annotation Validation Attributes

眉间皱痕 提交于 2020-01-04 06:56:31

问题


Is there any way to set Data Annotation messages using formatted string instead of direct constant,

I need to set required field ErrorMessage like in following code, but it gives me an error.

[Required(ErrorMessage = string.Format(SystemMessages.Required, "First Name"))]
public string FirstName { get; set; }

SystemMessages is a constant file and it has following code,

public const string Required = "{0} is required.";

Is there any way to set attributes like this?


回答1:


string.Format result is not a compile time constant and can't bee evaluated by the compiler. Attribute values are limited to

constant expression, typeof expression or array creation expression of an attribute parameter type.

More formally, you can find description of limitations at msdn. Formatting a string doesn't fit any of them, which are:

  • Simple types (bool, byte, char, short, int, long, float, and double)
  • string
  • System.Type
  • enums
  • object (The argument to an attribute parameter of type object must be a constant value of -one of the above types.)
  • One-dimensional arrays of any of the above types

At best you can try something similar to:

[Required(ErrorMessage = "First Name" + Required)]
public string FirstName { get; set; }


public const string Required = " is required.";



回答2:


Just use DisplayAttribute, if you want to output display name instead of property name:

[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }



回答3:


Please implement IValidatableObject which use Validate method. It will look like:

  public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
  {
       var memberNames = new List<string>();
       if (string.IsNullOrEmpty(this.FirstName )
        {
            memberNames.Add("FirstName");
            yield return new ValidationResult(string.Format(Resources.Required, "First Name"), memberNames);
        }
  }

If it is not clear please just read about IValidatableObject. Good luck!



来源:https://stackoverflow.com/questions/16913732/string-format-in-data-annotation-validation-attributes

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