Java Script: Number Validation

 Java Script     sbo     Updated on Nov 10, 2014     VIKRAM     559   

Introduction:

In this article i will explain how to validate a Number in Java Script.

Description:

In previous articles i explained How to replace string in Java ScriptHow many ways we can replace the string in Java ScriptHow to work with TextBox in Java ScriptHow to create a HTML Table dynamically in Java Script, and How to Create/Insert rows dynamically to HTML Table and Remove/Delete rows from HTML Table in Java Script. Now i will explain how to validate a Number in Java Script.

This article includes the following:

  1. Number Validation in Java Script
  2. Restrict user to enter other than numbers in onkeypress event.
  3. Number Validation in onblur event.

Number Validation:

Create a design as shown below.

    <div>
        <table>
            <tr>
                <td>
                    Enter Number
                </td>
                <td>
                    :
                </td>
                <td>
                    <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return validate();" />
                </td>
            </tr>
        </table>
    </div>

Now write a script to validate the number as shown below.

    <script type="text/javascript">
        function validate() {
            var txtNumber = document.getElementById('<%=txtNumber.ClientID %>');
            if (!validateNumber(txtNumber.value)) {
                alert('Enter Numbers only.');
            }
        }
        function validateNumber(num) {
            if (num.length <= 0) {
                return true;
            }
            else {
                var reg = new RegExp(/^\d+?$/); //only digits [0-9] allowed.
                return (reg.test(num));
            }
        }
    </script>

Here when submit button is clicked then validate() function will be called. It will get TextBox element by id. Then it will call validateNumber() function, it will return true or false based on regular expression and the value. If it returns false then alert message will be displayed.

Output:

After Loading.

After Submit.

Restrict user to enter other than numbers in onkeypress event:

Instead of validating data in submit click, we can restrict user to enter data other than numbers in onkeypress event.

Add onkeypress event to TextBox as shown below.

<asp:TextBox ID="txtNumber" runat="server" onkeypress="validateNumberOnKeyPress(this)"></asp:TextBox>

Read more on key codes in Java Script here.

Now write a script for validateNumberOnKeyPress()  function as shown below.

        function validateNumberOnKeyPress(evt) {
            if (typeof (evt) !== 'undefined') {
                var keycode = (evt.which) ? evt.which : event.keyCode;
                if ((keycode >= 48 && keycode <= 57) || keycode === 8) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }

Now it will restrict user input other than numbers.

Output:

Number Validation in onblur event:

What is the necessity to handle Number validation in onblur event?

In the above example we can restrict the user to enter the data, if they paste string it will not be validated. It will be validated in submit button click. To make user alert we will add onblur event. This will validate the TextBox when focus of the TextBox is lost.

Add onblur event to TextBox as shown below.

<asp:TextBox ID="txtNumber" runat="server" onkeypress="return validateNumberOnKeyPress(this);"
                        onblur="return validateNumberOnBlur(this);"></asp:TextBox>

Write script as shown below.

        function validateNumberOnBlur(sender) {
            if (!validateNumber(sender.value)) {
                alert('Enter Numbers only.');
                sender.value = '';
                sender.focus();
            }
        }

Internally it will call validateNumber() function.

Note:

We are dealing with server side controls so in each function (e.g. OnClientClick, onblur, and onkeypress) declaration return key word is mandatory.

  Related Articles
Check/Uncheck checkboxes when parent checkbox is checked/unchecked and vice-versa in Java Script
Java Script: Create/Insert rows dynamically to HTML Table and Remove/Delete rows from HTML Table
Java Script: Create HTML Table dynamically
Java Script: TextBox
Java Script: Get Key Codes
  Recent Articles
Check/Uncheck checkboxes when parent checkbox is checked/unchecked and vice-versa in Java Script
Java Script: Create/Insert rows dynamically to HTML Table and Remove/Delete rows from HTML Table
Java Script: Create HTML Table dynamically
Java Script: TextBox
Java Script: Get Key Codes