1

I am trying to override the default validation css class for validators which is "field-validation-error" class

So, if I write a Validation message for a input on my form as below:

@Html.ValidationMessageFor(m=>m.Name)

Then the MVC runtime is setting the class of the message span by default as below:

<span class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="Name">

My question is, how can I remove the css class "field-validation-error" and replace it with another class (my version) which i will be using it in only some areas of my application.

2 Answers 2

3

Ok...so I got it working by setting the base "field-validation-error" class as "form .field-validation-error" in the root css file...which means that this class will have the highest priority when the Html is generated and then in my View I included the new css class as mentioned below:

@Html.ValidationMessageFor(m=>m.Name, new { @class ="NewCssClass"})

This will generate the below markup:

<span class="field-validation-error NewCssClass" data-valmsg-replace="true" data-valmsg-for="Name">

As you can see the NewCssClass will override the default validation style specified in the "field-validation-error" class...

Cheers...

Sign up to request clarification or add additional context in comments.

1 Comment

are we missing the second param there? Please correct me if I am wrong.
0

Edit, you're right, I didn't read that far through the MVC source - just read the extension method source. Turns out those fields are static readonly with no options to change.

So, you're stuck with one of two choices:

  1. Deal with using the set class names.
  2. Write your own extension methods (or easier, just copy them from the MVC source and rename them).

3 Comments

thanks for the reply, the thing is HtmlHelper.ValidationInputCssClassName is a readonly field and cannot be set from your view???...
Read more source and fixed my answer. Less than ideal though.
I like option C: don't use MVC validation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.