Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Number validation in JavaScript

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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.



<!DOCTYPE html>
<html lang="en">
        Number validation in JavaScript
        /* this function is called when we
              click on the submit button*/
        function numberValidation() {
            let n = document.form.numbers.value;
            if (isNaN(n)) {
                    .innerHTML = "Please enter Numeric value";
                return false;
            } else {
                    .innerHTML = "Numeric value is: " + n;
                return true;
    <img src=
         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" />



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

My Personal Notes arrow_drop_up
Last Updated : 02 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials