Validating Numbers

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
1
2
3
4
$('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
1
2
3
4
5
$('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 to the some individuals. It could be worthwhile to also validate against these cases and to prevent a jarring user experience when inputting in forms.