Tuesday, October 18, 2011

ASP.NET Validation Controls and Styles

PROBLEM: RequiredFieldValidator with Display="Dynamic" places display:inline on the error text when displayed (and I want it to be display:block)

SOLUTION: Well there is no elegant solution! Sometimes the rapid development tools that are normally so helpful in .net just aren't flexible enough to allow what you want to do. The issue is discussed here: http://www.stackoverflow.com/questions/2243498.

Essentially when the validator is first displayed it sets (via .net generated javascript) style="display:none" on the span tag. This element then gets switched from "none" to "inline" when there is an error to display.

Your options?

1. Modify the automatic asp.net javascript - not nice, and could possibly break after future upgrades or browser changes etc. - but probably your best bet if you are desperate - here is how: http://caliberwebgroup.blogspot.com/2009/02/overriding-javascript-in-webresourceaxd.html

2. Roll your own validation controls - possible but then you lose all the default out of the box goodness that come with the asp.net validator controls.

3. Live with it. I went with this option. Sometimes 95% is good enough.

1 comment:

  1. There is a simple solution which will work now and in the future.

    1) Add a class to the validator
    2) Use jquery to add an inner element, like this, or use javascript if no jquery available:

    function wrapValidators() {

    $('.input-error').wrapInner('&lt span class="block" /&gt');
    }

    3) add css to block class "display:block"

    Done!

    ReplyDelete