ValidationSummary Tricks

I've become something of an ASP.NET validation geek lately.  I've been porting a bunch of pages from ASP to ASP.NET and the validation bits turned out to be extremely useful.  The default validators are pretty useful, but I've found myself writing a number of custom validators, so I wrote up an article on writing Custom Validators in the ASP.NET 2.0 Framework to document my various discoveries.

There's a couple of points that I've found very helpful that didn't fit into the article.  First of all, though it's not obvious, it is possible to customize an error message in the client-side validation routine.  The routine you declare takes a single argument which is the DOM node representing the validator on the page.  A client side validation routine like the following will build an error message dynamically.  The trick is figuring out a cross-browser innerText; there are more slick ways to do this by manipulating the prototype for the DOM node.

function RestrictedLengthValidatorEvaluateIsValid(val) {
  var value = ValidatorTrim(ValidatorGetValue(val.controltovalidate));
  var result = (value.length <= val.maxlength);
  if (result == false) {
    var errMsg = "This control can have a maximum of " + 
      val.maxlength + " characters, you have entered " + 
      ValidatorTrim(value).length + 
      ".  Please remove the extra characters.";
    if (val.textContent) {
      val.textContent = errMsg;  // FireFox
    } else if (val.innerText) {
      val.innerText = errMsg;  // IE & Opera
    }
  }
  return result;
}

The second point involves the ValidationSummary control.  This control provides a way to group validation results together.  The control is pretty well documented, but a couple of things should be highlighted.  First of all, individual validators support Text and ErrorMessage properties.  If a ValidationSummary is present, the summary will display the ErrorMessage, while Text will be displayed at the point where the validator is declared in the page.  The Text property supports HTML markup, so you can use something like an <img /> tag to put an icon where the validator is declared; if you declare your validator next to the control to be validated, you have a great visual cue for the control that's invalid.  Second, your validators will take up space on the page by default because when the validator is in a valid state, the validator's element is styled with visibility:hidden; you can change this to use display:none (and consequently take up no space when in a valid state) by setting the validator's display property ValidatorDisplay.Dynamic.

Finally, Milan Negovan's Pimpin' ValidationSummary with CSS is an excellent article on, well, pimpin' out your validation summary with CSS.  Check it out.

— Gordon Weakliem at permanent link