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?
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.
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.
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.
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.
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" })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With