0

I have a asp.net CheckBox and I have a textbox, I only want textbox to validate when checkbox is checked otherwise just leave it like this.

I find MVC post but I want for asp.net forms Validating textbox only if checkbox is checked using MVC

This is my current code which validates textbox regardless of checkbox is checked or not,

<asp:TextBox ID="txtSubject" runat="server" />
<asp:CheckBox ID="chkSubjectRequired" runat="server" />
<asp:RequiredFieldValidator ID="rfvSubject" ControlToValidate="txtSubject" ErrorMessage="You must enter a subject." runat="server" />
Community
  • 1
  • 1
Mathematics
  • 7,314
  • 25
  • 77
  • 152

3 Answers3

0

You will need a custom validator ,then:

<asp:TextBox ID="txtSubject" runat="server" />
<asp:CustomValidator ControlToValidate="txtSubject" OnServerValidate="IsTextboxValid" Text="Text box is invalid" runat="server"/>

In code behind,define custom validation method:

protected void IsTextboxValid(object sender,ServerValidateEventArgs e)
{
    e.IsValid=chkSubjectRequired.Checked;

}

Please note that this is Server-side Validation

Vikram
  • 675
  • 6
  • 25
0

this is what you looking for. Just enable/disable the validator (also textbox if you want) that's all.

Community
  • 1
  • 1
Onur Topal
  • 3,042
  • 1
  • 24
  • 41
-1

Validate The Text Box Only Number :

   <input type="text" onkeydown="ValidateNumber(event);">

    <script>
    function ValidateNumber(e) {
    if ((e.keyCode >= 8 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
        return true
    }

    return false;
};

Mahaveer Jangid
  • 366
  • 2
  • 11