Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

how to verify that input is an integer or float?

Posted on 2004-10-13
8
Medium Priority
?
2,879 Views
Last Modified: 2012-06-27
Hello,
I need to verify that user input from a textbox is a float or an integer. Non-numeric data has to be rejected. I need to do this in javascript.

Cheers,
Rick
0
Comment
Question by:richardsimnett
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 15

Accepted Solution

by:
Colosseo earned 2000 total points
ID: 12295445
Hi Rick

Here is an example page I created for you which should do what you need

<html>
<head>
<title>Check Number</title>
</head>
<script type="javascript">
<!--

  function validateNumber(num)
  {
    // If the input is not a number
      if(isNaN(num))
      {
        // alert the user and return false
        alert("You must enter a valid number!");
        return false;
      }
      // return true
      return true;
  }

//-->
</script>

<body>

<input name="txtNumber" type="text">

<input type="button" name="butValidate" value="Validate" onclick="validateNumber(txtNumber.value);">
</body>
</html>

Any questions let me know

Cheers

Scott
0
 
LVL 6

Expert Comment

by:etmendz
ID: 12296253
Use regular expressions.

To match float: /^[0-9]+\.[0-9]+$/

To match integer: /^[0-9]$/

Test for float first. If that fails, then test for integer. If that fails, there are invalid characters in the text box.

var fr = new RegExp("^[0-9]+\.[0-9]+$");
var ir = new RegExp("^[0-9]+$");

if (fr.Test(x)) {
 alert("Float!");
} else if (ir.Test(x)) {
 alert("Integer!");
} else {
 alert("Invalid number!");
}

Have fun.
0
 
LVL 6

Expert Comment

by:etmendz
ID: 12296288
Sorry, a little VBScript mixup there: Here's the correct code:

<html>
<head>
<script language="JavaScript">
function boo() {
      var fr = new RegExp("^[0-9]+\.[0-9]+$");
      var ir = new RegExp("^[0-9]+$");
      var x = "12.50";
      if (fr.exec(x) != null) {
            alert("Float!");
      } else if (ir.exec(x) != null) {
            alert("Integer!");
      } else {
            alert("Invalid number!");
      }
}
</script>
</head>
<body onload="javascript:boo();">
</body>
</html>
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 15

Expert Comment

by:Colosseo
ID: 12296340
:etmendz

Hi

I believe your first code didn't work cause you used Test instead of test.

I was thinking would you not want to check for an integer first. The way you have it an integer would match your float regexp?

Or instead just use

if ((fr.Test(x)) || (ir.Test(x))) {
 alert("Number!");
} else {
 alert("Invalid number!");
}

also your regular expressions don't allow for negative numbers

Cheers

Scott
0
 
LVL 6

Expert Comment

by:etmendz
ID: 12296420
To support signed numbers:

To match float: /^[+\-]?[0-9]+\.[0-9]+$/

To match integer: /^[+\-]?[0-9]$/

     var fr = new RegExp("^[+\-]?[0-9]+\.[0-9]+$");
     var ir = new RegExp("^[+\-]?[0-9]$");
     var x = "-12.50";
     if (fr.exec(x) != null) {
          alert("Float!");
     } else if (ir.exec(x) != null) {
          alert("Integer!");
     } else {
          alert("Invalid number!");
     }

Have fun.
0
 
LVL 3

Expert Comment

by:Tyzer
ID: 12297638
Just use  "isNaN"
Greetz, Tys
0
 
LVL 5

Expert Comment

by:kollu
ID: 12301010
function ValidateString(objName)
{
      var numberfield = objName;
      if (chkNumeric(objName) == false)
      {
            //numberfield.select();
            //numberfield.focus();
            return false;
      }
      else
      {
            return true;
      }
}                              
function chkNumeric(objName)
{
      var checkOK = "0123456789";
      //checkOK = checkOK + chr(8) + chr(127);
      var checkStr = objName;      
      var allValid = true;
      //alert("Len of object " + checkStr.value.length);
      for (i = 0;  i < checkStr.length;i++)
      {
      ch = checkStr.charAt(i);
      for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
      break;
      if (j == checkOK.length)
      {
      allValid = false;
      break;
      }
      }
      if (!allValid)
      {      
      alertsay = "Please enter only these values ";
      alertsay = alertsay + checkOK ;
      //alert(alertsay);
      return (false);
      }
}
Can check like
f (ValidateString(frmname.all["filed"].value)==false)
0
 
LVL 6

Expert Comment

by:etmendz
ID: 12304597
The advantage of facilitating the validation of numbers and their format may be useful when you want to have reusable javascript functions to specifically validate float for money or percent fields and integer for quantity fields for example.

Although isNaN may be enough to validate a numeric entry, it does not, however, enforce the validation of numeric formats. You can achieve the same effect as isNaN with regular expressions but you can be more flexible and specific with the fomat as necessary.

To simply validate a number (float or integer) using regular expression and reject invalid characters, use the regular expression:

/^[0-9]+(\.[0-9]+)?$/

To support signed numbers:

/^[+\-]?[0-9]+(\.[0-9]+)?$/

To support accounting format entries where "(#)" is for negative #:

/^([0-9]+(\.[0-9]+)?|\([0-9]+(\.[0-9]+)?\))$/

Have fun...
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question