[javascript] Check if input is number or letter javascript

I'm using forms in HTML and javascript. I would like an alert to pop up only if the user inputs a LETTER and clicks submit.

So I have the HTML code:

<form name="myForm" action="" onsubmit="return checkInp()" method="post">
    First name: <input type="text" name="age">
<input type="submit" value="Submit">   

And the javascript code:

function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (x consists of any letters) // this is the code I need to change
{
alert("Must input numbers");
return false;
}
}

This question is related to javascript html forms input

The answer is


I think the easiest would be to create a Number object with the string and check if with the help of isInteger function provided by Number class itself.

Number.isInteger(Number('1')) //true
Number.isInteger(Number('1 mango')) //false
Number.isInteger(Number(1)) //true
Number.isInteger(Number(1.9)) //false

I know this post is old but it was the first one that popped up when I did a search. I tried @Kim Kling RegExp but it failed miserably. Also prior to finding this forum I had tried almost all the other variations listed here. In the end, none of them worked except this one I created; it works fine, plus it is es6:

    const regex = new RegExp(/[^0-9]/, 'g');
    const val = document.forms["myForm"]["age"].value;

    if (val.match(regex)) {
       alert("Must be a valid number");
    }
   

you can use isNaN(). it returns true when data is not number.

var data = 'hello there';
if(isNaN(data)){
  alert("it is not number");
}else {
  alert("its a valid number");
}

A better(error-free) code would be like:

function isReallyNumber(data) {
    return typeof data === 'number' && !isNaN(data);
}

This will handle empty strings as well. Another reason, isNaN("12") equals to false but "12" is a string and not a number, so it should result to true. Lastly, a bonus link which might interest you.


Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.

function checkInp()
{
    var x = document.forms["myForm"]["age"].value;
    if ((x%1) != 0) 
    {
        alert("Must input numbers");
        return false;
    }
}

Try this:

if(parseInt("0"+x, 10) > 0){/* x is integer */}

The best and modern way is typeof (variable) if you care about real number not number from string. For example:

var a = 1;
var b = '1';

typeof a: // Output: "number"
typeof b: // Output: "string

You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    if (isNaN(x)) // this is the code I need to change
    {
        alert("Must input numbers");
        return false;
    }
}

Note: isNan considers 10.2 as a valid number.


Use Regular Expression to match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[a-zA-Z]+$/;
    if (!x.match(regex))
    {
        alert("Must input string");
        return false;
    }
}

Even better would be to deny anything but numbers:

function checkInp()
{
    var x=document.forms["myForm"]["age"].value;
    var regex=/^[0-9]+$/;
    if (x.match(regex))
    {
        alert("Must input numbers");
        return false;
    }
}

Thanks, I used @str8up7od answer to create a function today which also checks if the input is empty:

    function is_number(input) {
        if(input === '')
            return false;
        let regex = new RegExp(/[^0-9]/, 'g');
        return (input.match(regex) === null);
    }

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?