check box validation for atleast one check box should cheked in asp.net
I have asp.net form having 4 check boxes. not check box list. these 4 check boxes having the ValidationGroup property with same name say "chkValied". I have added Custom Validator t开发者_C百科here. now want to check at least on check box should be check out of these. what to do ?
You can use CustomValidator to validate input at client-side or server-side code.
aspx markup
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
<asp:CheckBox ID="CheckBox4" runat="server" />
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="put here error description"
ClientValidationFunction="clientfunc"
OnServerValidate="CheckValidate">
</asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
.cs (code-behind)
protected void CheckValidate(object source, ServerValidateEventArgs args)
{
args.IsValid=false;
if (CheckBox1.Checked)
args.IsValid = true;
if (CheckBox2.Checked)
args.IsValid = true;
if (CheckBox3.Checked)
args.IsValid = true;
if (CheckBox4.Checked)
args.IsValid = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (IsValid)
{
//valid
}
else
{
//Invalid
}
}
JavaScript code
<script type="text/javascript">
function clientfunc(sender, args) {
args.IsValid = false;
if (document.getElementById("CheckBox1").checked)
args.IsValid = true;
if (document.getElementById("CheckBox2").checked)
args.IsValid = true;
if (document.getElementById("CheckBox3").checked)
args.IsValid = true;
if (document.getElementById("CheckBox4").checked)
args.IsValid = true;
}
</script>
Try this article
http://weblogs.asp.net/samirgeorge/archive/2009/05/02/checkboxlist-client-side-validation-using-jquery.aspx
https://web.archive.org/web/20211020153246/https://www.4guysfromrolla.com/webtech/tips/t040302-1.shtml
If you are using custom validator such thing could be achieved with an or-statement:
if (chkBox1.Checked || chkBox2.Checked || chkBox3.Checked)
{
// At least 1 checkbox was checked.
}
This applies to all languages (although || is not universal all languages has a representation of it). In JavaScript you'd want .Value instead of .Checked.
精彩评论