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?
-
why not have the textbox disabled and when the user checks the checkbox enable the textbox?Juan– Juan2014-03-18 19:24:08 +00:00Commented Mar 18, 2014 at 19:24
-
@SaverioTerracciano It's a conversion of a classic site. All of the functionality has to match that of the old site. I hoped to use a custom validation control, because I'm using a validation summary which looks exaclty like what they are doing in the old site.hollyquinn– hollyquinn2014-03-18 19:36:45 +00:00Commented Mar 18, 2014 at 19:36
4 Answers
In OnClientClick event you can call a javascript method which will do this validation for you.
This should point you in the right direction.
1 Comment
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";
}
1 Comment
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');
}
}
Comments
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....