How to Check for a Numeric Type in Javascript

JavaScript is a client-side scripting language that, among other things, allows developers to design web pages that alert users when they have provided invalid input. Web page forms often request numeric input, such as area codes. A web page developer can save users time and frustration by checking that this type of input is numeric, and, in the case of invalid data, alerting the user that he needs to re-enter the value.

Things You'll Need

  • A web browser with JavaScript enabled.
  • A text editor.
Show More

Instructions

  1. Declare the variable.

    • 1

      Declare a variable that will hold the value that will be tested. Typically, this value will come from the user's input on a form, although it may be directly assigned:

      var numericVar = 9;

    • 2

      Define a function that accepts the user's input as an argument, being careful to name the function something meaningful:

      function isNumber(numericVar) {

      //write code to check if the variable is numeric.

      }

    • 3

      Use JavaScript's isNaN() function to determine whether the passed-in value is numeric. The isNan() function determines whether a value is "not a number" and returns "false" if the value is of type numeric.

      //function definition

      function isNumber(numericVar) {

      //declare a variable to hold the return value from the isNan() function

      var NaNResult = isNaN(numericVar);

      //do something with the return value

      }

    • 4

      Return the function's result. If the function is designed to alert the user that she has entered non-numeric--invalid--data, the result can be written to the Web page or placed in an alert box. Alternatively, the result can be returned to the calling code for further processing.

      //function definition

      function isNumber(numericVar) {

      //declare a variable to hold the return value from the isNan() function

      var NaNResult = isNaN(numericVar);

      //do something with the return value

      alert(NaNResult);

      }

Tips & Warnings

  • The isNaN() function returns true if a value is NOT a number. If you are testing that a value IS a number, then isNaN() returns false.

  • The isNaN() function may not return the expected value for all numeric types. For example, isNaN('1/4'); returns true.

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured