hollyquinn
hollyquinn

Reputation: 652

Custom Validation when TextBox has value and CheckBox does not

I have a situauation that I need to check on a button click if the user has entered a value into a textbox, but have not checked a checkbox. They need to be advised that they can not enter a value in the textbox without first checking the checkbox. I know I need to use a CustomValidator Control, but other than that I'm lost. Can anyone help me?

Upvotes: 0

Views: 1097

Answers (4)

Jameem
Jameem

Reputation: 1838

You can try this...

First you must have a button like this...

<asp:Button ID="btnCheck" runat="server" CssClass="m-btn purple" Text="Check" onclintclick="Validate()"/>

Now we can write the validation script...

<script type="text/javascript" language="javascript">
        function Validate() {

            if(document.getelementid('checkbox1').checked==true)
            {
              if(document.getelementid('Textbox1').value=="")
              {
               //Write your code here..
              }  
            }
            else
            {
               alert('Please check the checkbox..');
            }
        }
  </script>

Please feel free to mark as answer if it satisfies you....

Upvotes: 0

Unnie
Unnie

Reputation: 937

You can implement this functality using javascript/Jquery.Set the onClientClick property of button as below:

<asp:Button ID="btnSubmit" runat="server" onClientClick="ValidateData();"/>

Below is the jquery code:

function ValidateData()
{
if(!$('#checkboxID').is(':checked') && $.trim($('#textBoxID').val())!='')
{
alert('Please check the checkbox before entering text');
}

}

Upvotes: 0

sora0419
sora0419

Reputation: 2378

I think the easiest way to do so will be enabling/disabling the textbox base on whether the checkbox is checked.

However, if you want to do the check on button_click, maybe just do checks on both the checkbox and textbox? And output error message to a label or something?

if(TextBox1.Text.Trim() != "")
    if(!CheckBox1.Checked)
        label1.Text = "Checkbox needs to be checked";

Or, you can do checks when TextBox1.Text has changed.

private void Textbox1_TextChanged(object sender, EventArgs e)
{
    if(!CheckBox1.Checked)
        label1.Text = "Checkbox needs to be checked";
}

Upvotes: 1

AbhinavRanjan
AbhinavRanjan

Reputation: 1646

In OnClientClick event you can call a javascript method which will do this validation for you.

This should point you in the right direction.

Upvotes: 1

Related Questions