isNaN() function

We have used the isNaN() function for validation of the text field for numeric value only. When text-field data is passed into the function, if the passed data is a number or can be converted to a number, then isNaN() returns false. However, if the data is not a number or cannot be converted to a number, isNaN() returns true.

Example: This example shows the validation of the given number.

Javascript
function numberValidation(n) {

    if (isNaN(n)) {
        console.log("Please enter Numeric value");
        return false;
    } else {
        console.log("Numeric value is: " + n);
        return true;
    }
}

let num = 4;
numberValidation(4);

Output
Numeric value is: 4

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

Similar Reads

Approach 1: isNaN() function

We have used the isNaN() function for validation of the text field for numeric value only. When text-field data is passed into the function, if the passed data is a number or can be converted to a number, then isNaN() returns false. However, if the data is not a number or cannot be converted to a number, isNaN() returns true....

Approach 2: 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....

Contact Us