¿Cómo puedo hacer que se requiera una casilla de verificación en un formulario de ASP.NET?

votos
102

He hecho algunas búsquedas sobre esto, y he encontrado varias respuestas parciales, sin embargo, nada que me dé esa calurosa efusión de esta es la manera correcta de hacer esto. Para responder a la queja más frecuente contra esta pregunta: las casillas de verificación pueden tener dos estados legítimos, marcados y desmarcados, esta es una casilla de verificación Acepto los términos y condiciones ... que debe verificarse para completar un registro. por lo tanto, es necesario marcar la casilla desde el punto de vista de la lógica comercial.

¡Proporcione fragmentos completos de códigos listos para cortar y pegar con su respuesta! Sé que hay varias piezas en esto: el Custom Validator (presumiblemente), el código subyacente, algunos javascript y posiblemente un cheque para IsValid, y la parte frustrante para mí es que en cada ejemplo que he visto, uno de estos críticos piezas falta!

Publicado el 04/08/2009 a las 16:15
fuente por usuario
En otros idiomas...                            


6 respuestas

votos
-1

Forma no javascript . página aspx:

 <form id="form1" runat="server">
<div>
    <asp:CheckBox ID="CheckBox1" runat="server" />
    <asp:CustomValidator ID="CustomValidator1"
        runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>

Código detrás:

Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
    If Not CheckBox1.Checked Then
        args.IsValid = False
    End If
End Sub

Para cualquier acción que pueda necesitar (Reglas comerciales):

If Page.IsValid Then
   'do logic
End If 

Perdón por el código VB. . . puedes convertirlo a C # si ese es tu placer. La compañía para la que estoy trabajando ahora requiere VB :(

Respondida el 04/08/2009 a las 16:36
fuente por usuario

votos
202

función javascript para la validación del lado del cliente (usando jQuery) ...

function CheckBoxRequired_ClientValidate(sender, e)
{
    e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}

código subyacente para la validación del lado del servidor ...

protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
    e.IsValid = MyCheckBox.Checked;
}

Código ASP.Net para la casilla de verificación y validador ...

<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
    OnServerValidate="CheckBoxRequired_ServerValidate"
    ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>

y finalmente, en su devolución de datos, ya sea desde un botón o lo que sea ...

if (Page.IsValid)
{
    // your code here...
}
Respondida el 04/08/2009 a las 16:37
fuente por usuario

votos
17

C # versión de la respuesta de andrew:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
        ErrorMessage="Please accept the terms..." 
        onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    <asp:CheckBox ID="CheckBox1" runat="server" />

Código detrás:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = CheckBox1.Checked;
}
Respondida el 04/08/2009 a las 16:39
fuente por usuario

votos
4

respuesta de Scott trabajará para las clases de casillas de verificación. Si quieres casillas individuales, usted tiene que ser un poco más disimulados. Si acaba de hacer una caja, es mejor hacerlo con los ID. En este ejemplo se hace mediante casillas de verificación específicos y no requiere jQuery. Es también un pequeño ejemplo de cómo se puede conseguir esos identificadores de control molestos en su Javascript.

El Ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

Y el código subyacente:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub
Respondida el 18/02/2010 a las 00:06
fuente por usuario

votos
10

Si quieres un verdadero validador que no se basa en jQuery y trata la validación del lado del servidor, así (y debería hacerlo. Validación del lado del servidor es la parte más importante), entonces aquí es un control

public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
    private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
    protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
    {
        get
        {
            if (_ctrlToValidate == null)
                _ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;

            return _ctrlToValidate;
        }
    }

    protected override bool ControlPropertiesValid()
    {
        if (this.ControlToValidate.Length == 0)
            throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));

        if (this.CheckBoxToValidate == null)
            throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));

        return true;
    }

    protected override bool EvaluateIsValid()
    {
        return CheckBoxToValidate.Checked;
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        if (this.Visible && this.Enabled)
        {
            System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
            if (this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
            }
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
            {
                cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
            } 
        }
    }

    private string GetClientSideScript()
    {
        return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
    }
}
Respondida el 07/12/2011 a las 03:21
fuente por usuario

votos
2

Me suelen realizar la validación del lado del cliente:

<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server"  />
<asp:CustomValidator id="vTerms"
                ClientValidationFunction="validateTerms" 
                ErrorMessage="<br/>Terms and Conditions are required." 
                ForeColor="Red"
                Display="Static"
                EnableClientScript="true"
                ValidationGroup="vg"
                runat="server"/>

<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />

<script>
    function validateTerms(source, arguments) {
        var $c = $('#<%= chkTerms.ClientID %>');
        if($c.prop("checked")){
            arguments.IsValid = true;
        } else {
            arguments.IsValid = false;
        }
    }
</script>       
Respondida el 06/02/2015 a las 21:35
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more