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; } } 
                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.
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.
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!
isnan() isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number.
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;   } } 
                        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;     } } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With