How can I 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.
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
To solve this all within ASP.Net, make the checkbox do a postback:
<asp:CheckBox
ID="Existing"
runat="server"
Text="Conditional ValidatorVal"
AutoPostBack="True"
OnCheckedChanged="Existing_CheckedChanged"
/>
Then on the code-behind, enable or disable the validators:
protected void Existing_CheckedChanged(object sender, EventArgs e)
{
RequiredFieldValidator1.Enabled =! Existing.Checked;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With