user804401
user804401

Reputation: 1994

backspace not working during validation in firefox

I have written the below code so that users only enter numbers. It works fine in all the browsers excepts FireFox

In FireFox after entering a number if the users clicks backspace it is not working properly. Below is the code.

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript">

        function getKeyCodeFromEvent(e) {
            if (typeof e == "object" && typeof e.which == "number") {
                return e.which;
            }
            return window.event.keyCode;
        }

        function checkEntry(e) {
            var keyCode = this.getKeyCodeFromEvent(e);
            var regularExpression = /^[0-9.]+$/;
            return regularExpression.test(String.fromCharCode(keyCode));
        }

    </script>
</head>
<body>
    <input type="text" onkeypress="return checkEntry(event);" />
</body>
</html>

Upvotes: 1

Views: 1454

Answers (1)

nils
nils

Reputation: 27225

When someone presses the backspace key, you get the value 8 from getKeyCodeFromEvent. Running it in String.fromCharCode(8); then returns the following unicode value: ``. This does not match your regex, so it fails.

You could solve this by checking that the backspace, delete, tab, left and right keys are allowed, before turning them into String values. You will need to use the keydown event though, because keypress does not return values for certain keys, such as left or right.

Be careful when restricting user movement like this though, as it might easily make people angry, when the site doesn't work as they expect it to.

<script>

    function getKeyCodeFromEvent(e) {
        if (typeof e == "object" && typeof e.which == "number") {
            return e.which;
        }
        return window.event.keyCode;
    }

    function checkEntry(e) {

        var keyCode = getKeyCodeFromEvent(e);
        var regularExpression = /^[0-9.]+$/;

        // If the key is backspace, tab, left, right or delete
        if([8,9,37,39,46].indexOf(keyCode) !== -1 || e.ctrlKey || e.metaKey) {
            return true;
        }
        if(!regularExpression.test(String.fromCharCode(keyCode))) {
            e.preventDefault();
            e.returnValue = false;
            return false;
        }
    }

    // I took the liberty of moving your event from the HTML into JavaScript, where it belongs
    document.addEventListener("DOMContentLoaded", function() {
        document.getElementById('numberinput').addEventListener("keydown", checkEntry, false);
    }, false);
</script>
<input type="text" id="numberinput" />

http://jsfiddle.net/8hzwLjfz/6/

Upvotes: 1

Related Questions