The Self-Taught Programmer

Recipes from real-world experience with asp.net.

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

3 Responses

Subscribe to comments with RSS.

  1. Thanks, this is what I am looking for, but I tried using your code and I am getting Microsoft Jscript runtime error object expected

    lisa green

    May 29, 2012 at 4:40 pm

    • As you know, troubleshooting JavaScript is painful. I would look at a couple of things here: My function uses JQuery, so you have to have the JQuery library referenced on your page; also, make sure the JavaScript function references your checkboxlist by the correct name. In my example, I named my checkboxlist “cblConstructionType”, so in my function, I use “cblConstructionType.ClientID”.

      Hope this helps.

      Jim McMullen

      May 30, 2012 at 11:30 am

      • Thanks yes, it was the Jquery,I added and it works. thanks again

        lisa green

        May 31, 2012 at 11:38 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: