Required Errormessage dynamic content

Asked

Viewed 552 times

2

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

"Required field! [Social Reason]"

Normally I would do so:

[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 Required name in Errormessag in the Display. So when changing this value the name will be changed automatically in the message.

1 answer

4


An 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; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.