Here's a solution that I used in a recent website:
Since the asp:CustomValidator does not accept an asp:CheckBox as the control to validate, the first step is to set it to any other control in the page (e.g. a textbox).
The second step is to write a bit of JavaScript (JQuery) to return the non-checked state of the checkbox to validate. Below, I am showing a JavaScript variable being set, that is for use by the JavaScript method.
<script type="text/javascript">
var controlID1 = '<%= CheckBoxAgree.ClientID %>';
</script>
Here's the JavaScript function you'll need to write:
function IsNotChecked1(obj, args) {
var checkbox = $("#" + controlID1); args.IsValid = checkbox.attr('checked');}
Here's the code to include in the aspx page:
<asp:CheckBox ID="CheckBoxAgree" runat="server"Text="I confirm that the above information is accurate to the best of my knowledge and agree to the terms and conditions" />
<asp:CustomValidator ID="CustomValidatorAgree" runat="server" ClientValidationFunction='IsNotChecked1'
onservervalidate="CustomValidatorAgree_ServerValidate" ValidationGroup="group1" ControlToValidate="TextBoxTelephone"ErrorMessage="'I confirm' must be checked" ValidateEmptyText="True" ></asp:CustomValidator>
Note that above we are setting the control to validate to any other control in the page.
Since you must also validate on the server side (best practice), here's the C# code:
protected void CustomValidatorAgree_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = (CheckBoxAgree.Checked);
}
Kaynak:
http://forums.asp.net/t/1054253.aspx/1?Checkbox+Validation+Best+Solution
http://tugberkugurlu.com/archive/how-to-validate-a-checkbox-in-asp-net-3-5-checkbox-validation-control-sample-code-in-asp-net-c-sharp-c-sharp-and-visual-basic
Hiç yorum yok:
Yorum Gönder