How to make a Textbox required IF a Checkbox is checked

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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;
}

Method 3

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.

Method 4

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.

Method 5

You must use CustomValidator and use ClientIDMode=”Static” in checkbox and textbox.

<asp:TextBox ID="txtSubject" ClientIDMode="Static" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" ClientIDMode="Static" runat="server" />
<asp:CustomValidator ID="valid1" runat="server" 
           ClientValidationFunction="validateCheckboxCheck" 
           ErrorMessage="You must write anything.">
</asp:CustomValidator>

And write below script tag for function (require jQuery)

<script type="text/javascript">
function validateCheckboxCheck(source, args) {
            if ($("#chkSubjectRequired").is(":checked")) {
                if ($("#txtSubject").val()==="") {
                    // return false for error message
                    args.IsValid = false;
                } else {
                    // return true
                    args.IsValid = true;
                }
            } else {
                // return true
                args.IsValid = true;
            }
        }
</script>

Method 6

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x