Search code examples
asp.netcustomvalidatorsetfocus

SetFocusOnError for CustomValidator is not working


I have some controls with CustomValidators like following. However the SetFocusOnError is not working, the page doesn't jump to the first control if validation fails. I could set focus in the javascript, but the problem with it is that always the last control that is not valid gets the focus, which is not what I want, I want the first control that is not valid gets the focus.

Can anyone tell me how to fix this? Thanks.

function ValidateRootCause(source, args) {
    var status = document.getElementById("<%=statusDropDownList.ClientID %>");
    var RootCause = document.getElementById("<%=txtRootCause.ClientID %>");

    args.IsValid = true;
    if (RootCause.value == "" && (status.value == 21 || status.value == 18)) {
        args.IsValid = false;
        RootCause.focus();
    }
}

        <tr>
            <td width="45%">Root Cause (Why it Happens)<span class="littlefont">*</span>                
            <asp:CustomValidator ID="cvRootCause" runat="server" 
                    ErrorMessage="Required Field!" CssClass="warning" 
                    ClientValidationFunction="ValidateRootCause" ValidationGroup="formValidation" SetFocusOnError="True">
            </asp:CustomValidator>
            </td>
            <td width="55%">

                <asp:TextBox ID="txtRootCause" runat="server" TextMode="MultiLine" 
                    MaxLength="1000"></asp:TextBox>
            </td>
        </tr>

Solution

  • Create a global (outside of your function) JavaScript variable called "focusGiven" or something like that. In your if(), wrap another if() check around your focus call. This way it will only happen once.

    var focusGiven = false;
    function ValidateRootCause(source, args) {
        var status = document.getElementById("<%=statusDropDownList.ClientID %>");
        var RootCause = document.getElementById("<%=txtRootCause.ClientID %>");
    
        args.IsValid = true;
        if (RootCause.value == "" && (status.value == 21 || status.value == 18)) {
            args.IsValid = false;
    
            if (!focusGiven) {
                RootCause.focus();
                focusGiven = true;
            }
        }
    }