Daniel Fisher (lennybacon.com)

SOA, DATA & THE WEB

Changing background color of a textbox from a CustomValidator’s client side script

I’m currently at a customer in Hannover and was asked how to change the background color of a textbox from the client side validation method called by a CustomValidator control.

Here is a sample how to access the pages validation properties including the one from the custom validator:

function validateRequired(sender, args)
{
    if (args.Value == null) return;
    if (args.Value.length > 0) return;

    args.IsValid = false;

    var txt = $get(sender.controltovalidate);
    if (txt)
    {
        txt.style.backgroundColor = '#ff0000';
    }
}

I wrapped the stuff in a server control derived from the custom validator control:

public class RequiredValidator
    : CustomValidator
{
    protected override void OnInit(EventArgs e)
    {
        var ctrl = Parent.FindControl(ControlToValidate);
        if (ctrl == null)
        {
            throw new InvalidOperationException(
                "ControlToValidate not found.");
        }
        var txt = ctrl as TextBox;

        if (txt == null)
        {
            throw new InvalidOperationException(
                "ControlToValidate is not a textbox.");
        }

        if (!Page.ClientScript.IsClientScriptBlockRegistered(
            typeof(CustomValidator), "RequiredValidator"))
        {

            Page.ClientScript.RegisterClientScriptBlock(
                typeof(CustomValidator),
                "RequiredValidator",
                string.Concat(
                    "<script type=\"text/javascript\">\n//<![CDATA[\n",
                    Resources.RequiredValidator,
                    "\n//]]>\n</script>"));
        }
        base.OnInit(e);
        ClientValidationFunction =
            string.Concat(
                "validateRequired");
        ServerValidate += RequiredValidator_ServerValidate;

        EnableClientScript = true;
        ValidateEmptyText = true;
    }

    private void RequiredValidator_ServerValidate(
        object source,
        ServerValidateEventArgs args)
    {

        var ctrl = Parent.FindControl(ControlToValidate);
        if (ctrl == null)
        {
            throw new InvalidOperationException(
                "ControlToValidate not found.");
        }
        var txt = ctrl as TextBox;

        if (txt == null)
        {
            throw new InvalidOperationException(
                "ControlToValidate is not a textbox.");
        }

        if (!string.IsNullOrEmpty(txt.Text)) return;

        txt.BackColor = Color.Red;
        args.IsValid = false;
    }
}

« MCPD ASP.NET 3.5 Nic is telligent now… »

Comments

Write a comment