views:

1062

answers:

4

Hi,

I have 2 textbox controls where date values will be entered. I want it so that if a date is entered into one of the textboxes then the other one becomes required.

This is probably a real noobie question but any help would be greatly appreciated.

Thanks in advance.

Edit: Just to clarify a bit better. I use a compare validator to check if the value entered into the textboxes are dates, so thats not a problem. The problem is that I want some validation so that if a value is entered into one textbox then the other one becomes required. Otherwise if both textboxes are left empty then neither are required.

A: 

Keep a disabled required field validator for textbox 2. Enable it in textchanged event of textbox1. Make sure you check the length of the text in textbox1 in the event as the TextChanged event will fire even if the user deletes the text entered in textbox1.

danish
A: 

If you are using the built in validation controls you could just enable/disable one for txtDate2 in the Page_Load method based on the value of txtDate1.

protected void Page_Load(object sender, EventArgs e)
{
   dateValidator2.Enabled != String.IsNullOrEmpty(txtDate.Text);
}

In your aspx file;

<asp:RequiredFieldValidator ID="dateValidator2" Enabled="false" runat="server" ErrorMessage="Some message"></asp:RequiredFieldValidator>
Kirschstein
+2  A: 

Well, you could do one of two things. First, as danish said, use the textchanged property of textbox1 to set the Enabled property of validator2 to true or false accordingly. Just make sure you set the autopostback property of textbox1 to true. This would look even better if you wrapped it in an update panel so the user didn't have to see the autopostback.

The other option is to use a custom validator control where you write the validation logic in the ServerValidate() event. Then, you can check if the text entered in textbox1 is a date and then validate textbox2 accordingly.

NYSystemsAnalyst
You can also specify the ClientValidationFunction so that it will validate both client-side and server-side.
Dave Anderson
Thanks this is what I was after.
Zaps
A: 

If you want the best user experience, this validation should be done client side.

The RequiredFieldValidator control actually produces javascript code to perform the validation on the client side, but it doesn't have the "both or none" capability that you're looking for.

So, the best solution would be to write the javascript yourself. There are a number of frameworks that make this easier. I suggest jQuery.

Matt Brunell