Writings & Photography of Derek Dysart, some dude you’ve never heard of.
Random header image... Refresh for more!

Styling ASP.NET Validation Controls

A little break from all the photography for a bit. Since I spent the better part of the morning trying to get around this, I figured I’d document it for future developers.

If you are using the intrinsic ASP.NET Validation controls on a Web Forms project, you’ll notice they always default to being red. While this is all fine and good since red for warnings makes sense.  What if you (or your design team) want them to be a different color?  If you look at the rendereded HTML, you’ll see it makes the text red by using inline CSS:

<span id=”ctl09_uxValidatorPostalCode” title=”Required Field” class=”scfRequired” style=”color:Red;”>*</span>

Where this becomes an issue is if you try to style this via an external stylesheet (generally a good practice):

.scfRequired {
color: #005598;
}

Since there is a color specified in the inline CSS, it will take precendent.  We could add !important to our external stylesheet, but that sort of feels like a hack.  What we really want to do is get ASP.NET to stop adding the inline style. Turns out this isn’t that hard to do.  Just add a blank ForeColor attribute to your validator:

<asp:RequiredFieldValidator ID=”uxValidatorPostalCode”
CssClass=”scfRequired”
ToolTip=”Required Field”
Text=”*”
ForeColor=”"
ControlToValidate=”uxPostalCode”
runat=”server”
ErrorMessage=”Please Enter your ZIP/Postal Code”></asp:RequiredFieldValidator>

No inline CSS colors will be output and your external stylesheet rules will apply. I’m sure this isn’t news to many, but none of the first few pages of search results seemed to point this out. This applies for all of the validation controls including the ValidationSummary control which seem to have a predisposition to red.