MVC3 Display an Asterisk For Error Message
So with when working with MVC3 you can decorate your POCO’s with attributes that can be used to validate the properties on both the server and client side. It makes validation easy.
But what if you don’t really have the space to display the error messages next to the field and would rather have something shorter like an asterisk?
Turns out the ValidationMessageFor HtmlHelper takes a parameter for validationMessage which overrides the ErrorMessage from the model.
The POCO and a strongly typed view:
using System.ComponentModel.DataAnnotations;
namespace MvcApplication3.Models
{
public class Person
{
[Required(ErrorMessage = "The name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "The title is required")]
public string Title { get; set; }
}
}

Then update your view’s ValidationMessageFor with a second parameter, a string containing your new error message.
@Html.ValidationMessageFor(model => model.Name, "*")

And if you want to display a list of the error messages set the ValidationSummary parameter to false (display all errors):
@Html.ValidationSummary(false)

One more thing, if you are using your own style sheet, our custom errors are displaying:

We just have to hide the custom error messages from view until someone tries to submit the form with one CSS class.
.field-validation-valid
{
display: none;
}
Source for the CSS: http://stackoverflow.com/questions/4370131/asp-net-mvc-3-rc-razor-validationmessagefor-custommessage-and-clientsidevalidat
Leave a Reply