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 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.
Below is a code in HTML and JavaScript to validate a text field if it contains a digit or not.
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title > Number validation in JavaScript </ title > < script > /* this function is called when we click on the submit button*/ function numberValidation() { event.preventDefault(); let n = document.form.numbers.value; if (isNaN(n)) { document.getElementById("numberText") .innerHTML = "Please enter Numeric value"; return false; } else { document.getElementById("numberText") .innerHTML = "Numeric value is: " + n; return true; } } </ script > </ head > < body > < img src = alt = "Avatar" style = "width: 200px;" /> < form action = "#" name = "form" onsubmit = "numberValidation()" > Number: < input type = "text" name = "numbers" /> < span id = "numberText" ></ span > < br /> < input type = "submit" value = "submit" /> </ form > </ body > </ html > |
Output:

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