ASP.NET validators messing up the layout of your web form

The validator controls on ASP.NET are a quite handy way to validate user input. They perform a check twice. In the browser some snippets of script block a postback to the server as long as the user input does not fulfill the requirements. They thus prevent unnecessary roundtrips. When the data does reach the server it is validated again. All of this works quite nice. But when it comes to the layout validators can have some unexpected behavior. Take this fragment of a web form.

The upper two textboxes have two validators: input is required and should fall within a certain range. This is what the page will look like in the browser when the second validator fails:

The first validator does not show up as text but as you might see it does show up as a blanks. Forcing the second validation text to the right  resulting in a text wrap. By default the validator controls always emit html. When the input is invalid it emits the message in red else it emits a string of non blank spaces. This happens also when validation makes no sense, for instance because the associated control is read-only.

ASP.NET wouldn’t be if you could not change this behavior. The validator controls have a Display property. It’s default value is static, resulting in the spaces demonstrated. When you set it to Dynamic it only outputs something when the validation condition is not met. A third value is None, in which case it will never emit anything.

This entry was posted in ASP.NET. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Rd1089

    Thank you.

  • Paul

    Thanks, this saved me time.

  • pvanooijen

    didn’t I say that clear enough already 😕 What’s missing ?

  • Goofy

    set the setting Display=”Dynamic”, problem solved when you run the project.