mercredi 28 mai 2008

Validation de checkbox: cocher au moins une case

Dans mon formulaire, j'ai 2 Checkbox, l'utilisateur doit cocher au moins une sinon les 2.

J'ai placé les 2 cases à cocher et le validateur dans un UserControl. La validation se fait à l'aide d'une fonction javascript.

Voici le UserControl:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CheckBoxControlMatSoir.ascx.cs" Inherits="Controls_DataEntryControls_CheckBoxControlMatSoir" %>

<script language="javascript" type="text/javascript">
function
ValidateTandCs(source, args)
{
var chkMat = document.getElementById('<%= CheckBoxMat.ClientID %>');
var chkAprem = document.getElementById('<%= CheckBoxAprem.ClientID %>');

if ((chkMat.checked) || (chkAprem.checked))
{
args.IsValid = true;
}

if ((chkMat.checked==false) && (chkAprem.checked==false))
{
args.IsValid = false;
}
}
</script>

<
br />
<
asp:CheckBox ID="CheckBoxMat" runat="server" Text="Matinée" ForeColor="Navy" />
&nbsp;&nbsp; &nbsp;
<asp:CustomValidator ID="valTandCs" ClientValidationFunction="ValidateTandCs" runat="server"
ErrorMessage="*" Height="1px"></asp:CustomValidator><br />
<
asp:CheckBox ID="CheckBoxAprem" runat="server" Text="Après-midi" ForeColor="Navy" />





Le code behind:

C#

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Controls_DataEntryControls_CheckBoxControlMatSoir : System.Web.UI.UserControl
{
private bool m_mat_checked = false;
private bool m_aprem_checked = false;


protected void Page_Load(object sender, EventArgs e)
{
m_mat_checked = CheckBoxMat.Checked;
m_aprem_checked = CheckBoxAprem.Checked;
}


public object MatChecked
{
get { return m_mat_checked; }
set
{
if (value.GetType() == DBNull.Value.GetType()) m_mat_checked = false;
else if (value == null) m_mat_checked = false;
else if (value.GetType() == typeof(bool)) m_mat_checked = (bool)value;
else m_mat_checked = false;
}
}

public object ApremChecked
{
get { return m_aprem_checked; }
set
{
if (value.GetType() == DBNull.Value.GetType()) m_aprem_checked = false;
else if (value == null) m_aprem_checked = false;
else if (value.GetType() == typeof(bool)) m_aprem_checked = (bool)value;
else m_aprem_checked = false;
}
}

protected void Page_PreRender()
{
CheckBoxMat.Checked = m_mat_checked;
CheckBoxAprem.Checked = m_aprem_checked;
}

}





Dans la page aspx, il suffit d'insérer le UserControl. Je fais également un Binding grâce aux propriétés MatChecked et ApremChecked du UserControl.

<uc1:CheckBoxControlMatSoir ID="CheckBoxControlMatSoir1" runat="server" 
MatChecked='<%# Bind("matin") %>' ApremChecked='<%# Bind("soir") %>' />

1 commentaire:

oudinia a dit…

It's Great. I have some comments if you don't mind.
it would be very nice to have some comments on the C# code. one comment by property or so.