Open In App

Number validation in JavaScript

Last Updated : 05 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Approach

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

We have a complete list of Number methods, to check those please go through this JavaScript Number Complete Reference article.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads