Wednesday, October 12, 2011

Mandatory CheckBox

Problem: The RequiredFieldValidator doesn't allow you to enforce that a CheckBox in asp.net is checked/selected.

Solution: Best approach I could find was to simply use a CustomValidator (ideally with client and server side validation but server side would be sufficient). Example code is as follows:

ASPX PAGE:


ClientValidationFunction="ValidateTermsAndConditionsAgreement"
OnServerValidate="ValidateTermsAndConditionsAgreement"
runat="server"
Text=" You must agree to the terms and conditions before entering. "
ValidationGroup="vgEntryDetails"
CssClass="error"
Display="Dynamic">

CODE BEHIND:

Since I was actually optionally displaying my checkbox I actually added the validation script optionally in Page_Load (note, it needs to be done regardless of whether Page_Load is being called as part of a postback or not otherwise if there is a postback before you click submit the javascript you've injected via the code behind won't be there and hence the client side validation will not work).

//Script to use as part of the page validation
if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "TermsAndConditionsScript"))
{
string scriptText = " function ValidateTermsAndConditionsAgreement(sender, args){" +
" if (document.getElementById('" + chkAgreeToTermsAndConditions.ClientID + "').checked){" +
" args.IsValid = true;" +
" }" +
" else {" +
" args.IsValid = false;" +
" }" +
" return;" +
"}";

Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"TermsAndConditionsScript", scriptText, true);
}

...and the server side validation

///
/// Validate that the terms and conditions have been agreed to if they exist
///
///
///
protected void ValidateTermsAndConditionsAgreement(object source, ServerValidateEventArgs args)
{
if (chkAgreeToTermsAndConditions.Checked == false)
{
args.IsValid = false;
}
}


...and finally don't forget to check IsValid in your method called by the submit button.


protected void btnSubmitEntry_Click(object sender, EventArgs e)
{
//Is valid check is required because we have a CustomerValidator control
//for the terms and conditions checkbox - if it's not valid we don't want to proceed and the error will be
//displayed.
if (Page.IsValid)
{
//Save competition entry
....

No comments:

Post a Comment