Required ErrorMessage dynamic content

2

Using Asp.Net MVC 5 I need to create a required message in the following format:

  

"Required field! [Registered name]"

Normally it would look like this:

[Required(ErrorMessage = "Campo de preenchimento obrigatório! [Razão Social]")]
[Display(Name = "Razão Social")]
[StringLength(60)]
public string RazaoSocial { get; set; }

I would like to use the ErrorMessag of Required or Name that is in the Display. So by changing this value the name will change automatically in the message.

    
asked by anonymous 30.03.2015 / 22:28

1 answer

4

One option would be to create a static class and put the different types of messages there:

public static class ValidationMessage
{
    public const string Required = "Campo de preenchimento obrigatório! [{0}]";
    public const string StringLength = "O campo {0} deve conter entre {2} e {1} caracteres.";            
}

And in your class:

[Required(ErrorMessage = ValidationMessage.Required)]
[StringLength(60, ErrorMessage = ValidationMessage.StringLength)]
[Display(Name = "Razão Social")]
public string RazaoSocial { get; set; }
    
30.03.2015 / 23:40