The Self-Taught Programmer

Recipes from real-world experience with asp.net.

Posts Tagged ‘Validation

How to Require a Textbox Be Completed When “Other” is Selected in a CheckBoxList

with 3 comments

The Situation:

You have a CheckBoxList with an “Other (please specify)” option at the end. If the visitor selects “Other”, you want to require that they fill out the “Other” textbox as shown here:

'Other' in checkboxlist

You will need to use a Custom Validator attached to the “Other” text box.

ASPX file:

<asp:CheckBoxList ID="cblConstructionType" runat="server" RepeatColumns="3" RepeatDirection="Vertical">
    <asp:ListItem Value="Dormitory">Dormitory</asp:ListItem>
    <asp:ListItem Value="Hospital">Hospital</asp:ListItem>
    <asp:ListItem Value="Playground">Playground</asp:ListItem>
    <asp:ListItem Value="Residential">Residential</asp:ListItem>
    <asp:ListItem Value="Water/Sewer">Water/Sewer</asp:ListItem>
    <asp:ListItem Value="Other (please specify below)">Other (please specify below)</asp:ListItem>
</asp:CheckBoxList>

<div id="FieldsOtherConstructionTypes" runat="server">
    <label for="tbOtherConstructionType">If 'Other', please specify:</label>
    <asp:TextBox runat="server" ID="tbOtherConstructionType" Columns="40" MaxLength="250"></asp:TextBox>
    <asp:CustomValidator ID="cvOtherConstructionType" runat="server" 
            ClientValidationFunction="validateOtherField" OnServerValidate="ValidateOtherField" 
            ValidateEmptyText="true" ControlToValidate="tbOtherConstructionType" 
            ErrorMessage='You must fill in the "other" box.' Display="Dynamic">
        <asp:Image ID="Image34" runat="server" ImageUrl="~/images/yellow-warning_16px.gif" />
    </asp:CustomValidator>
</div>

Client Validation

The client validation function using jQuery will look like this:

<script language="javascript">
<!--
	function validateOtherField(sender, args) {
		args.IsValid = true;

		$('#<%= cblConstructionType.ClientID %> input:checked').each(function () {
			if ($('label[for="' + $(this).attr('id') + '"]').text() == "Other (please specify below)") {
				if (args.Value == null || args.Value == "") {
					args.IsValid = false;
				}
			}
		});
	} // end validateOtherField

-->
</script>

Line 6 of this javascript function uses jQuery to loop through each checked item in the CheckBoxList (as a CheckBoxList, there can be multiple checked items) and runs a function (lines 7-12) that looks for the label attached to the ListItem. If it finds “Other (please specify below)”, it then checks to see if the texbox is null or empty (not the same thing). Because the CustomValidator is attached to the tbOtherConstructionType textbox, ‘args.Value’ refers to value entered into that textbox.

Why set args.IsValid = true in line 4, you ask? Because if you added an “else” statement after line 10 to set it to true, then every time the code looped, it could possible reset IsValid back to “true” even if it was already set to “false”. This way, the value is assumed true and is only set to false if stated conditions are met.

IMPORTANT NOTE: You must set the ValidateEmptyText attribute of the Custom Validator to “true” or it will not fire if the field is blank. This is a quirk of the CustomValidator control.’

Sever Validation

The server validation is easier to understand and looks like this:

protected void ValidateOtherField(object source, ServerValidateEventArgs args)
{
	switch (cblConstructionType.SelectedValue.ToString())
	{
		case "Other (please specify below)":
			if (args.Value.Length > 0)
			{
				args.IsValid = true;
			}
			else
			{
				args.IsValid = false;
			}
			break;
		default:
			args.IsValid = true;
			break;
	}
}

This is pretty standard server-side validation. I used a switch here because I think it looks cleaner, but I could as easily have used an “If” statement instead.

Advertisements

Written by Jim McMullen

April 18, 2011 at 11:34 pm

Posted in How-To

Tagged with