Tuesday 16 March 2010

Use EnableValidator to Manage an ASP.NET Validator in Client Script

I’m a big fan of the ASP.NET validator controls—not because they’re complete and wonderful but because they’re convenient when they work as expected and otherwise keep me on my toes when something out of the ordinary is required.

Today brought forth a requirement to hide the State field on a form when the country wasn’t set to Australia. Because the State field also has a RequiredFieldValidator attached, I would have to disable the validator server-side in some cases during the initial page load (depending on the data being pre-filled) and disable it client-side as the user interacts with the form. Failing to do so would prevent the form from posting back when the State field was hidden.

One of the main reasons I like these validation controls so much is because of the way they just work client-side and server side; in the client arena, everything occurs as Javascript and that was enough for me to assume, in this case, I could manage the validator through Javascript. I wasn’t certain this would be possible (or at least simple) but fortunately I won’t lose any sleep over this one tonight ;) As I found out, changes to a validation control in one context are even reflected in the other—nice!

The magic all happens with the mysterious ValidatorEnable(validator, bool) function. I have no idea where this function comes from and don’t really care but it allows you to enable or disable a validator in Javascript code by supplying the validator object and a boolean value indicating whether it should be enabled (true) or disabled (false).

It’s important to remember the first parameter is the validator object itself, not its ID. You’ll need to locate the validator object by ID (or using some other means) of course, but that’s where the ClientID property comes in handy:

var stateRequiredFieldValidatorId = "<%=rqdState.ClientID %>";

For additional information check out the ancient (circa 2002) “ASP.NET Validation in Depth” article on MSDN. Jonas Bush also has a concise example.

1 comment:

  1. http://www.w3cvalidahttp://www.w3cvalidation.net/tion.net/http://www.w3cvalidation.net/


Spam comments will be deleted

Note: only a member of this blog may post a comment.