snippetjavascriptTip
Validate a number in JavaScript
Viewed 0 times
javascriptnumbervalidate
Problem
Number validation is probably one of the hardest things to do even for intermediate developers. However, it's a necessary evil, especially when working with user input. It's even more so in JavaScript, due to the language's quirks and the fact that it's loosely typed.
While, a simple check that
And, as if that wasn't already enough, you also need to check if the coercion of the value to a number is correct, using
While, a simple check that
parseFloat() produces a sensible numeric value might seem enough, it's a little more involved than that. You also need to check for NaN, using Number.isNaN(), and for Infinity, using Number.isFinite().And, as if that wasn't already enough, you also need to check if the coercion of the value to a number is correct, using
Number() and the loose equality operator (==). Putting everything together, you get a pretty robust number validation function.Solution
const validateNumber = n => {
const num = parseFloat(n);
return !Number.isNaN(num) && Number.isFinite(num) && Number(n) == n;
}
validateNumber('10'); // true
validateNumber('a'); // falseAnd, as if that wasn't already enough, you also need to check if the coercion of the value to a number is correct, using
Number() and the loose equality operator (==). Putting everything together, you get a pretty robust number validation function.Code Snippets
const validateNumber = n => {
const num = parseFloat(n);
return !Number.isNaN(num) && Number.isFinite(num) && Number(n) == n;
}
validateNumber('10'); // true
validateNumber('a'); // falseContext
From 30-seconds-of-code: number-validation
Revisions (0)
No revisions yet.