Search code examples
cssunobtrusive-validation

Using CSS to style labels pointing to elements with a certain attribute


I am using unobtrusive validation in an ASP.Net MVC3 app. I would like to style the label elements associated with required elements in a certain way.

My concern is not to tweak the visual indicators around the required field itself, but to modify the appearance of a different element based on the attributes of this element.

Now, I believe it would be possible to style the elements themselves just with CSS by using a CSS rule whose selector applied to all elements with the [data-val-required] attribute. It would look something like this:

input[data-val-required] { color: red; }

But is it possible to style the labels? To say (with a CSS selector) that a CSS rule applies to all label elements whose for attribute points to an input element that has the [data-val-required] attribute?

I'm currently applying styling with a little bit of jQuery currently, and it works nicely. But it would be even nicer if I could just set up a CSS rule and be done with it.


Solution

  • You can't get there from here. As @vlgalik says, the only CSS options are selectors that are 1) not supported on some browsers, and 2) have limited ability to find other elements, forcing you to construct your markup to comply.

    So, your current solution -- use JQuery to find the labels and their corresponding inputs -- is your best bet.

    However, I'd approach your jQuery solution in the opposite direction: first find all the inputs matching input[data-val-required], and for each of those, get its ID, then select the corresponding label: label[for="<id-from-input>"] -- that seems like it will be less work. But that's an optimization; if you don't have a lot of labels and inputs on the page, either direction will work fine.