Using typeof Operator
Using the typeof operator for number validation in JavaScript verifies if a variable is of type number. However, it doesn’t guarantee the value’s numeric validity; additional checks like isFinite() are needed for robust validation, ensuring finite numeric values.
Example: In this example, isFinite() ensures that the value is a finite number, excluding NaN and Infinity. While typeof can provide a basic level of validation, for more robust number validation, consider using additional checks tailored to your specific requirements, such as isNaN(), isFinite(), or regular expressions.
function validateNumber(value) {
if (typeof value === 'number' && isFinite(value)) {
console.log('Valid number');
} else {
console.log('Not a valid number');
}
}
validateNumber(123);
validateNumber('abc');
validateNumber(NaN);
validateNumber(Infinity);
Output
Valid number Not a valid number Not a valid number Not a valid number
Number validation in JavaScript
Sometimes the data entered into a text field needs to be in the right format and must be of a particular type in order to effectively use the form. For instance, Phone number, Roll number, etc are some details that must be in digits not in the alphabet.
There are some apporaches:
Table of Content
- isNaN() function
- Using typeof Operator