JavaScript Number Validation Example


In this JavaScript tutorial, we will validate the numeric value in the text box. Sometimes we need to restrict the user that you can enter only the numeric type value, not alphabets in the particular fields.

For example, the mobile number can’t be alphabets its must be numeric values.

9892929292 is a valid mobile number.

981AX343p2 is not a valid mobile number.

To validate the mobile number field values, create a function, call it on onkeypress event and check the keyCode value.

JS Snippet
function numbersOnly(e) {
    if (!(e.keyCode >= 48 && e.keyCode <= 57)) {
        return false;
    } else {
        return true;
    }
}

Check the Full Example

<!DOCTYPE html>
<html>
    <head>       
        <title>JavaScript Number Validation Example</title>
        <script type="text/javascript">
            function numbersOnly(e) {
                if (!(e.keyCode >= 48 && e.keyCode <= 57)) {
                    document.getElementById("msg").innerHTML = "Sorry! only numbers allowed.";
                    return false;

                } else {
                    document.getElementById("msg").innerHTML = "";
                    return true;
                }
            }
        </script>
    </head>
    <body>
        <h1>JavaScript Number Validation Example</h1>
        <label>Enter the Mobile Number:</label>
        <input type="text" name="number" onkeypress="return numbersOnly(event);">
        <span id="msg" style="color: red;"></span>
    </body>
</html>

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.