views:

455

answers:

5

Whats the best way to make a textbox required if a checkbox is checked?

I figure I could write a custom validator, but I was hoping to avoid a full post back to check the validation if possible... I was thinking AJAX had something built in for this scenario, but I've been unable to find it. I'm thinking straight Javascript would also be a solution, but I could use a head start if that's the best approach.

Thanks for any info.

+2  A: 

You could make a custom validator, and then wrap those two controls in an UpdatePanel. That would turn it into an AJAX call for you. Kinda a waste, but it saves you having to write the JavaScript yourself.

Also, if you hate writing JS as much as I do, you should try jQuery instead.

mgroves
A: 

I'm not sure but I think you should take a look at the UpdatePanel, i think you can work something out with that component

sebastian
A: 

You'll need to check for it in whatever validation routine you're currently using, both client and server-side.

Tequila Jinx
A: 

Hey,

There is already a customvalidator validator control, which can fire a client-side javascript method to evaluate the value, or a server-side method to compare the values.

This has an example: http://msdn.microsoft.com/en-us/library/a0z2h4sw%28VS.80%29.aspx Client property explained here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.clientvalidationfunction.aspx Server event here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.servervalidate.aspx

You can put code in to cross-reference the checkbox value.

HTH.

Brian
+4  A: 

The JavaScript to handle this isn't very difficult.

Given the following ASP controls:

<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" OnClick="updateValidator();" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" ErrorMessage="You must enter a subject." runat="server" />

Add the following JavaScript function:

<script language="javascript" type="text/javascript">
    function updateValidator() {
        var enableValidator = !event.srcElement.status;
        var rfvSubject = document.getElementById('rfvSubject');
        ValidatorEnable(rfvSubject, enableValidator);
    }
</script>

That's all there is to it. You will also want to add the following code to your Page Load event, so that if the user has JavaScript disabled, your required field validator is still turned on or off properly:

rfvSubject.Enabled = chkSubjectRequired.Checked
Jason Berkan
awesome thanks much...although looking at your asp code, wouldn't that txtSubject be required even when the checkbox wasn't checked? Did you mean to disable the validator...then have the javascript enable it?
Albert
All provided code is untested blah blah blah. Yeah, looks like I got that backwards. I have modified my answer.
Jason Berkan
cool just wanted to check. thanks again
Albert