Question

I have 2 asp.net textboxes in an update panel. Both textbox controls have some javascript attached to autotab to the next field and to allow only numeric input. When I enter some data into the first field and press enter, focus shifts to the next field and the requiredfieldvalidator of the second field displays its "* required" error message, even though I've just entered the field. How can I prevent the validator from firing when I first enter the textbox?

I should also mention that both textboxes are in a gridview footer.

Here's the code:

<asp:TextBox ID="add_ISBN" runat="server" Columns="14" MaxLength="17" CssClass="focus" />
<asp:TextBox ID="add_Qty" runat="server" Columns="4" MaxLength="4" />
<asp:RequiredFieldValidator ID="rfvQty" ControlToValidate="add_Qty" ErrorMessage="* required" ForeColor="Red" Display="Dynamic" EnableClientScript="true" ValidationGroup="Add" runat="server" />

In the codebehind:

 add_ISBN.Attributes.Add("onkeydown", "return isbnCheck(event, '" & add_Qty.ClientID & "')") 

And the javascript:

function isbnCheck(e, id) {
    e = e || window.event;
    var key = e.which || e.keyCode

    if (validIsbnChars.indexOf(parseInt(key, 10)) >= 0) {
        return true;
    } else {
        if (key == 13) {
            var nextfield = document.getElementById(id);
            if (nextfield) nextfield.focus();
            return false;
        }
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;
        return false;
    }
}

The javascript allows only a valid subset of characters, and if the user presses enter, sets focus to the next field.

Was it helpful?

Solution 2

I managed to fix this by attaching the javascript to the onKeyPress event instead of onKeydown.

add_ISBN.Attributes.Add("onkeydown", "return isbnCheck(event, '" & add_Qty.ClientID & "')") 

OTHER TIPS

I'm not sure why the bug is happening, but you can probably create a workaround using the client-side validation mini-api.

Find the validator element on the page doing a document.getElementById(), and then set the isvalid flag to true on the validator when you tab into the field.

Alternately you could call ValidatorEnable(validatorElement, false) to disable it while you're in the field, and then re-enable it with ValidatorEnable(validatorElement, true) when you tab out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top