Validating Numbers

12/24/2014, Wed
Categories: #JavaScript
Tags: #jQuery

Is the content intended to be a number?

When dealing with validations in input forms, one occasionally has to determine if the content entered is actually a number. However, the input content will always be string when performing a check on an input.

// Always a String

$("input").on("change", function () {
  // Outputs 'string'
  console.log(typeof $(this).val());
});

Although this behavior is convenient for most situations, it could be a hassle for numbers.

To solve this problem, parseInt will be used.

// String to Number

$('input').on('change', function() {

  // Outputs 'string'
  // The '10' is for decimal form
  console.log(typeof parseInt($(this).val(), 10);
});

Want to point out that my validator function could be used in place of typeof.

Mathematically Inclined Cases

Besides representing numbers as integers or decimal, there are also situations where numbers could be negative or positive zero or represented in exponential form. There are even more extreme cases such as infinity.

For these cases, the numbers representations are valid, but may be unusual for some individuals. It could be worthwhile to also validate against these cases and to prevent a jarring user experience when inputting in forms.