How to check Entered Value in TextBox is Number or not in JavaScript


Sometimes we stuck in a situation like we have to take only integer number from textbox and leave if the value is not a number in JavaScript…

we have the solution with isNaN() function in JavaScript see this example to understand clearly.

Example :

JavaScript:

<script type="text/javascript">
        function CheckNumberOrNot() {
            var Age = document.getElementById("Age");
            var result = isNaN(Age.value);
            if (!result) {
                alert("You are : " + Age.value + " years old.");
            } else {
                alert("Not recognized as Valid No.");
            }
        }
    </script>

 

Complete Code (Jsp):

<%@ Page Language="java" import="java.util.*" pageEncoding="ISO-8859-1" %>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>

    <script type="text/javascript">
        function CheckNumberOrNot() {
            var Age = document.getElementById("Age");
            var result = isNaN(Age.value);
            if (!result) {
                alert("You are : " + Age.value + " years old.");
            } else {
                alert("Not recognized as Valid No.");
            }
        }
    </script>

</head>
<body>
    This is my JSP page.
    <br />
    <br />
    Age:
    <input type="text" id="Age" name="Age">
    <br />
    <br />
    <input type="button" value="submit" onclick="CheckNumberOrNot();" align="center" />
</body>
</html>

OutPut :

FormDesign

Invalid Number

Valid Number

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s