Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply class to @Html.ValidationMessageFor

Tags:

asp.net-mvc

Model:

[Required(AllowEmptyStrings = false, ErrorMessage="Please enter student name.")]
[StringLength(20,ErrorMessage="Student name cannot be over 20 characters long")]
    public string StudentName { get; set; }

View:

@Html.ValidationMessageFor(m=>m.StudentName,new {@class = "validation"})

Seems like there is no such overload for ValidationMessageFor. How do I apply class to it?

like image 585
Dylan Czenski Avatar asked Jun 15 '16 17:06

Dylan Czenski


People also ask

What is validationmessagefor in ASP NET MVC?

ASP.NET MVC: ValidationMessageFor. The Html.ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object.

How to add a CSS class to the displayed validation message?

The Html.ValidationMessageFor Helper method has a parameter named htmlAttributes which is used for adding (applying) CSS Class (Styles) to the displayed validation message. Please refer the following article for complete information on how to configure Bundles and enable Client Side validation in ASP.Net MVC project.

How do I use the validationmessagefor () method for the studentname?

The following view uses the ValidationMessageFor () method for the StudentName . In the above example, the first parameter in the ValidationMessageFor () method is a lambda expression to specify a property for which we want to show an error message.

How to validate form without student name in ASP NET MVC?

Now, when the user submits a form without entering a StudentName then ASP.NET MVC uses the data- attribute of HTML5 for the validation and the default validation message will be injected when validation error occurs, as shown below. The error message will appear as the image shown below.


2 Answers

I just looked this up.

So in your case try:

@Html.ValidationMessageFor(m=>m.StudentName,""/* or null or what you want the error message to be */, new { @class = "validation" })
like image 189
Grizzly Avatar answered Oct 19 '22 23:10

Grizzly


By default it should be using .field-validation-error class.

All you have to do is customize that css.

.field-validation-error {
    color: red;
}

If you really want to change that class name to 'validation', then I do not know how.

like image 31
Rosdi Kasim Avatar answered Oct 20 '22 00:10

Rosdi Kasim