Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Thursday 28 May 2015

In this article I will explain how to apply validation (allow only numeric value) on textbox using Javascript. I have entered only numeric values in textbox and alphabets or special characters are not allowed.


In this article I have a TextBox for which I have specified three event handlers, onkeypress, ondrop and onpaste.

On the onkeypress event handler, I am making call to a JavaScript function IsNumeric. This function determines the ASCII code of the keyboard key is within the range 48 to 57. Also it makes sure that the key pressed is not a special key like Backspace or Delete, if yes it will ignore the character.
On the ondrop event handler, I have simply written return false so that the dropping functionality on the TextBox is disabled.
On the onpaste event handler, I have simply written return false so that the pasting functionality on the TextBox is disabled.

Following Javascript Function we will use for Validation:
<script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        function IsNumeric(e) {
            var keyCode = e.which ? e.which : e.keyCode
            var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
            document.getElementById("error").style.display = ret ? "none" : "inline";
            return ret;
        }
    </script>

Full Source Code for Sample Application:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        body
        {
            font-size: 9pt;
            font-family: Arial;
        }
    </style>
</head>
<body><fieldset style="width:400px">
    <legend><strong>Numeric Validation On Textbox using javascript</strong></legend>
    <br />
    Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
    <span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
    <script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        function IsNumeric(e) {
            var keyCode = e.which ? e.which : e.keyCode
            var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
            document.getElementById("error").style.display = ret ? "none" : "inline";
            return ret;
        }
    </script></fieldset>
</body>
</html>


0 comments:

Post a Comment