Unbreakable
Unbreakable

Reputation: 8084

Validation error message displays the entire text of the property in Asp.Net MVC 5

So, I have one view with a textbox in it and I am trying to manipulate the error message when user does not put any value in that text field in my ASP.Net MVC 5 project. Below is the model

[Display(Name = "Enter verification token sent to your email"), Required]
public string Token{ get; set; }

Now the problem is when user does not put any value I get below message in my screen

The Enter Verification Token sent to your email field is required.

Now as you can see the error message is taking it's text from the Display attribute of the property of the corresponding Model. But the error message is lengthy and confusing. Honestly, it does not make proper sense too. How to manage these situations. I am a beginner so I do not know many nuances of it but how experienced developer manage error message. Can we have a lengthy Display attribute and still tell ModelState validation to show a different short error message. Do, I need to manually add ModelState.AddModelError, or I am thinking too much?

How about displaying an error message as "Token field is required"

Upvotes: 1

Views: 1136

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23210

an we have a lengthy Display attribute and still tell ModelState validation to show a different short error message.

Yes. By using ErrorMessage property available on your Required attribute like this:

[Display(Name = "Enter verification token sent to your email"), 
 Required(ErrorMessage="Token field is required")]
public string Token{ get; set; }

Do, I need to manually add ModelState.AddModelError, or I am thinking too much?

No you don't need it. It is too much.

Upvotes: 2

Related Questions