Conditionally enable fieldvalidators (ie RequiredFieldValidator) in Asp.Net

Today i used the old and familiar asp.net validators again.
The code was straight forward: controls where dynamicly created and their validators, dynamicly, also.
But in this case i wanted to use the validators conditionally, which is not an uncommon thing todo:

Say you order a book. You have to enter your delivery address, so that field is mandatory so you attach a RequiredFieldValidator to it. Then there is a checkbox ‘use another address for invoicing’. When you check it, the invoice address is mandatory, but when you uncheck it, the address must be optional (and probably disabled, but that’s another thing). The solution: conditionally (based on the condition ‘is checkbox checked?’) the invoce address textbox validator must do it’s work; it must be enabled or disabled.

The Asp.Net validators are split into two parts:
a client side validation and a server side validation.
For the client side there is a simple javascript function (which is generated by the .Net framework when you use .NEt validators) for enabling the validator:

 ValidatorEnable(CONTROL, enableValidator);

I’ve called it with Jquery with a change event on the checkbox: if the control is checked, call ValidatorEnable(txtInvoiceAddress, true); when the control is un-checked, call ValidatorEnable(txtInvoiceAddress, false).

On the server side, it’s almost as simple: you have to override the ‘Validate’ event:

public override void Validate()
{
  if (chkUseOtherAddress.Checked)
  {
  ReqValidatortxtInvoiceAddress.Enabled = true;
  }
  else
  {
  ReqValidatortxtInvoiceAddress.Enabled = false;
  }
  base.Validate();
}

And then you’re good to go. The client side part makes sure the average user get’s client side validation; the server side validation validates the user who bypass the normal page or have Javascript disabled.

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