views:

175

answers:

4

I have 2 TextBoxes (textBoxA, textBoxB), both watched by their own RequiredFieldValidator. I want to 'enable' the RequiredFieldValidator for textBoxB just when textBoxA has a value (or meets some specific conditions).

Use cases:

Case 1 textBoxA = ""; -> Show Required Field Validation Message textBoxB = ""; -> Do not show validation message

Case 2 textBoxA = "has a value"; textBoxB = ""; -> Show Required Field Validation Message

Case 3 textBoxA = "has a value"; textBoxB = "has a value too";

Thanks for your help!!

+2  A: 

In this situation I'd use a CustomValidator for textBoxB instead of the required field validator. In the server side validation method you can control the exact nature of the validation with something like this.

if (textBoxA.Text != string.Empty)
{
    args.IsValid = textBoxB.Text != string.Empty;
}
Craig M
Thanks for the response, that'll work for server side validations, but I'll have some dependant validations on the same page, and I don't want that that many postbacks
tivo
A: 

I don't believe there's a declarative way to do it. I've always done this by having a ValidatePage method where I set my validators to enabled or disabled and then call Page.Validate at the end (and then proceed or render based on Page.IsValid).

So, either

validator2.IsEnabled = textBoxA.Text.Trim().Length > 0

or something like that.

That's pseudo code btw...I haven't done ASP.NET in some time now.

Rich
+2  A: 

You might want to use a CustomValidator to do this. You'll need to implement the client side and server side validation. Something like (off the top of my head and untested)

Server side

protected void ServerValidation (object source, ServerValidateEventArgs args)
{      
   if (!string.IsNullOrEmpty(textBoxA))
       args.IsValid = !string.IsNullOrEmpty(textBoxB);

}

Client Side

function clientValidation(sender, args) {
    if (args.value !== "") {
       var textBoxB= document.getElementById('textBoxB');
       args.IsValid = (textBoxB.value !== "");
    }
    return;
}
Russ Cam
A: 

Validating conditionally with validation groups using manually calling validation functions , http://tinylink.in/VL

Priyan R