Wednesday, February 16, 2011

Simple ListBox Validator

I ran into a situation today where I was copying values from a TextBox to a ListBox and before submitting the form, I needed to validate that there were actually values in the ListBox. Sounds simple enough, right? At first I tried using a RequiredFieldValidator and it seemed to work. But, I was able to get the form into a state where it was incorrectly flagging the ListBox value as invalid. Here is a simple ListBox validator that I wrote for this situation.

using System.Web.UI.WebControls;
public class ListBoxRequiredFieldValidator : CustomValidator
    public ListBoxRequiredFieldValidator()
        EnableClientScript = true;
        ValidateEmptyText = true;

    protected override void OnPreRender(EventArgs e)
        ClientValidationFunction = 
                string.Concat(ClientID, "_ValidateRequiredListBox");
        string validatedcontrolclientid = 
        const string scriptFormat =

        var script = string.Format(scriptFormat,
                string.Concat(ClientID, "_ValidationScript"), script);

No comments:

Post a Comment