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.
Approach
We have used isNaN() function for validation of the text field for numeric value only. Text-field data is passed in the function and if passed data is a number then isNan() returns true and if data is not a number or a combination of both number and alphabets then it returns false.
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.
Last Updated :
13 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...