ASP.Net Custom Validators and Empty Controls…

Recently with work I have been forced to had a chance to do some web development in ASP.Net. There was a particular part of the web site that required some custom validation on a DetailsView. One field was required, and another one was required only if a CheckBox in the DetailsView was checked. This ruled out using a RequiredFieldValidator on the second field, as it could be left blank. The way around this? Use a CustomValidator.

I figured it would be pretty simple to do, and it was. But to get it working properly took me a little while to figure out. According to the MSDN documentation, a CustomValidator doesn’t fire if the contents of the control it is validating is empty, by default. This made debugging it a bit of a chore, as I couldn’t figure out why the validator wasn’t stopping things like it should have. Eventually I came across this gem in the comments of another blog post:

… ValidateEmptyText=”true” …

Setting this flag means the CustomValidator will fire regardless of the contents of the control it is validating.

In the words of Shell Busey, “It’s just that easy.”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s