views:

44

answers:

2

Hi I need to validate two fields in an Asp.net form, where the requirements is like any one of them is required. For example, there is Page title and sub-heading input boxes, so any one of them is required. Can I do it using the validation controls Asp.Net provides?

Any kind of help is greatly appreciated. Thanks in advance.

+1  A: 

You can use a CustomValidator control (MSDN) in ASP.NET for special situations that are not supported by any one of the other standard validators. It was created for this reason.

Microsoft describes how to create a custom validation function here.
Here's another tutorial on implementing it.

Or if you google for keywords like "creating a custom validator in asp.net" you can pick and choose from various solutions for your own project.

John K
From the custom validator you can check both input fields using whatever logic you need. In this kind of situation the custom validator's .ControlToValidate property becomes somewhat irrelevant.
John K
+1  A: 

For your case, as an alternative to using a CustomValidator, you could explicitly change whether your required field validators are enabled by using the ValidatorEnable() JavaScript function.

// disable validation control
ValidatorEnable(RequiredFieldValidator1, false);

You can then write custom logic in JavaScript to determine the case in which each validation control is either enabled or disabled, and tie it to one of the (client-side) events of the text boxes (onblur, onchange, onkeyup, etc).

Then, on the server side you can write similar logic to do the same thing by setting the "Enabled" property and put this logic in your button click event before you check the IsValid state.

If all you are doing is conditionally determining when something is required, changing the enabled state is your best bet. Exactly what can be done is documented in ASP.NET Validation In Depth.

NightOwl888
If you're creating custom logic for both the server- and client-side then you're effectively doing what needs to be done for a custom validator control. Why then side-step integration with the ASP.NET validation system by working outside a custom validator? I question the benefit.
John K