开发者

ASP.NET required field validator firing on focus in firefox

开发者 https://www.devze.com 2022-12-31 23:57 出处:网络
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 f

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" MaxLen开发者_如何学Cgth="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.


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.


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 & "')") 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号