验证复选框

时间:2013-04-25 13:59:10

标签: c# checkbox validation

我已经看了十几个以前的答案,这里对我没什么用。我需要一个表单,其中必须选中复选框才能提交。我正在使用C#并且它是新手,我发现使用文本框的RequiredFieldValidator不能用于复选框,所以我需要另一种方法来做到这一点。

提交时,字段中的数据会被发送到MS SQL数据库。我有更多字段然后显示如下所示,但我想我会为这篇文章压缩它并删除除了一个文本框之外的所有内容以及我需要在提交时验证的复选框。

我希望在提交时执行此操作:

enter image description here

<form id="form1" runat="server">
    <asp:Label ID="NameLbl" runat="server" Text="Label"></asp:Label><asp:RequiredFieldValidator
        ID="NameRFV" runat="server" ErrorMessage="NameTxtBox"></asp:RequiredFieldValidator>
    <asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="AliveLbl" runat="server" Text="Are you alive?"></asp:Label>
    <asp:CheckBox ID="AliveChkBox" runat="server" />
    <asp:Button ID="Submit" class="btn btn-primary" runat="server" Text="Submit"  OnClick="Submit_Click" />
</form>

我已经阅读过有关使用CustomValidator但我无法正常使用它的任何内容。人们一直说你需要编译/构建你的代码才能工作,我根本不知道怎么做。

也会考虑javascript选项。如果您知道更好的方法来验证这些,我也可以使用CheckboxList。

4 个答案:

答案 0 :(得分:0)

Submit_Click功能中,您可以添加AliveChkBox.Checked true是否为false的检查。如果是MessageBox,您可以显示return或类似内容,以通知用户需要对其进行检查,然后只需Submit_Click {{1}},这样才会发生任何事情。它被检查了。

答案 1 :(得分:0)

您想要使用

if (checkbox1.Checked) 
btn1.enabled

else (checkbox1.disabled)
btn1.disabled
this.errorProvider1.SetError(checkbox1, "Must be checked to continue"); 

答案 2 :(得分:0)

以下是解决方案:

代码背后:

using System;

public partial class TestCheckBox : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AliveScript", "<script>function CheckAlive(){ return document.getElementById('" + this.AliveChkBox.ClientID + "').checked; } </script>");

        this.Submit.OnClientClick = "return CheckAlive();";
    }
    protected void Submit_Click(object sender, EventArgs e)
    {

    }
}

aspx页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestCheckBox.aspx.cs" Inherits="TestCheckBox" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="NameLbl" runat="server" Text="Label"></asp:Label>
        <asp:RequiredFieldValidator ID="NameRFV" runat="server" ErrorMessage="NameTxtBox" ControlToValidate="NameTxtBox"></asp:RequiredFieldValidator>
        <asp:TextBox ID="NameTxtBox" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="AliveLbl" runat="server" Text="Are you alive?"></asp:Label>
        <asp:CheckBox ID="AliveChkBox" runat="server" />
        <asp:Button ID="Submit" class="btn btn-primary" runat="server" Text="Submit" OnClick="Submit_Click" />
    </form>
</body>
</html>

答案 3 :(得分:0)

if(checkBox1.Checked == true)                 button1.Enabled = true;

使用与此类似的代码,只需使其在属性

上未启用button1
相关问题