94

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;
}
}
2
  • Define “letter”. Is “é” a letter? What about “α”? If you mean Ascii letters from A to Z and from a to z, please say so. Commented Aug 4, 2013 at 11:43
  • 1
    You may also want to change the HTML. Switch <input type="text" /> to <input type="number" min="0" max="125" step="1" />. In modern browsers this will check for an numeric input without any JS. Commented Sep 26, 2014 at 10:53

11 Answers 11

141

You can use the isNaN function to determine if a value does not convert to a number. Example as below:

function checkInp()
{
  var x=document.forms["myForm"]["age"].value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    return false;
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Beware the empty string: isNaN('') === false; #jsrage
Don't do this, strings like '0xFF' and '2e32' will pass through this validation.
You cannot use this to check for numbers. It fails if an alphabet follows the number. Try this "3a".
And the craziest fact is NAN is also a number :(
this method is not reliable
|
58

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;
    }
}

3 Comments

Are you missing a ! before x.match(regex) in your second code snippet?
This is the cleanest solution
Or you mean regex.test(x) ?
15

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.

2 Comments

*isNaN -yes, that may be problem, is there any possible ways to input whole numbers only? Thanks for the answer.
For whole numbers only, use regex and take a look at my answer.
8

You can use isNaN(). It returns true when passing a value that is not a number.

var data = 'hello there';

if (isNaN(data)) {
  alert("it is not a valid number");
} else {
  alert("it is a valid number");
}

1 Comment

isNaN(true) returns false
7

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.

1 Comment

7

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");
    }
   

Comments

6

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;
    }
}

Comments

4

Try this:

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

4 Comments

or simply if ( (x >> 0) > 0 )
Worked grand also, except there is still the issue with the decimal numbers. Thanks a million for the answer though.
Could you guys explain in detail how does it work? What does >>operator means? Thanks in advance
Unfortunately, it gives 32 for "32!" instead of an error.
4

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

3 Comments

beware Number(''); //0
Number.isInteger('1') wont return true. it returns false. It will still read as string.
pass Number('1')
2

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);
    }

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.