Saturday, January 15, 2011

A Quick Fix for the Validator SetFocusOnError Bug

The ASP.NET validators have this nice property called "SetFocusOnError" that is supposed to set the focus to the first control that failed validation. This all works great until your validator control is inside a naming container. A ASP.NET blogger, David Findley, has a solution to it by overriding the Validate method on a page.

C# version:

public override void Validate(string group)
{
    base.Validate(group);

    // find the first validator that failed
    foreach (IValidator validator in GetValidators(group))
    {
        if (validator is BaseValidator && !validator.IsValid)
        {
            BaseValidator bv = (BaseValidator)validator;

            // look up the control that failed validation
            Control target = bv.NamingContainer.FindControl(bv.ControlToValidate);

            // set the focus to it
            if (target != null)
            target.Focus();

            break;
        }
    }
}

C# 3.0 and higher using LINQ:

public override void Validate(string group)
{
    base.Validate(group);

    // get the first validator that failed
    var validator = GetValidators(group)
        .OfType()
        .FirstOrDefault(v => !v.IsValid);

    // set the focus to the control
    // that the validator targets
    if (validator != null)
    {
        Control target = validator.NamingContainer.FindControl(validator.ControlToValidate);

        if (target != null)
            target.Focus();
    }
}

Visual Basic 2008 (VB.NET):

Public Overrides Sub Validate(ByVal group As String)
    MyBase.Validate(group)

    'find the first validator that failed
    For Each validator As IValidator In GetValidators(group)
        If (validator.GetType() Is GetType(BaseValidator) AndAlso Not validator.IsValid) Then
            Dim bv As BaseValidator = CType(validator, BaseValidator)

            'look up the control that failed validation
            Dim target As Control = bv.NamingContainer.FindControl(bv.ControlToValidate)

            'set the focus to it
            If target IsNot Nothing Then
                target.Focus()
            End If

            Exit For
        End If
    Next
End Sub

A Quick Fix for the Validator SetFocusOnError Bug [via]

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.