Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } } 
like image 215
Greg Peckory Avatar asked Aug 04 '13 10:08

Greg Peckory


People also ask

How do you check if input value is string or number?

To check if an input's value is a valid number in React: Check if the input's value is not an empty string or contains only spaces. Pass the value to the isNaN() function. If isNaN returns false , the value is a valid number.

How do you check if a given character is a number letter in JavaScript?

Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.

How do you check that the character is a string or number in JavaScript?

To check if a character is a number, pass the character as a parameter to the isNaN() function. The function checks if the provided value is NaN (not a number). If the function returns false , then the character is a valid number. Copied!

How do you check if a value is Not-a-Number in JavaScript?

isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.


2 Answers

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;   } } 
like image 94
Bat_Programmer Avatar answered Oct 07 '22 18:10

Bat_Programmer


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;     } } 
like image 31
Kim Kling Avatar answered Oct 07 '22 17:10

Kim Kling