0

I want to make the input accept only numbers! Please someone should tell me why the code below isn't working. (Aside HTML5 "tel"

<!DOCTYPE html> <html> <head> <title>Second Table</title> <link rel="stylesheet" type="text/css" href=""> </head> <body> <form method="post" action="something.php" name="myForm" onsubmit="return validateForm()"> <label>Your Mobile Number</label> <input id="mobileNumber" type="contact" name="phone" placeholder="Enter A Valid Mobile Number" required> <input type="submit" value="submit"> </form> <script> function validateForm(){ var mobileNumber = document.forms["myForm"]['mobileNumber'].value; if(mobileNumber == null || mobileNumber == ""){ alert("A Mobile Number Must Be Entered"); return false; } if(mobileNumber.length < 11 || mobileNumber.length > 11){ alert("Enter A Valid Number"); return false; } if(mobileNumber == /^[-+]?[0-9]+$/){ return true; } else{ alert("Numbers Only"); return false; } } </script> </body> </html>

15th Nov 2018, 4:37 AM
Nolan
Nolan - avatar
2 Antworten
+ 1
Your test for the RegExp [ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp ] Is not correct. It should either /^[-+]?[0-9]+$/.test(mobileNumber); or mobileNumber.match(/^[-+]?[0-9]+$/);
15th Nov 2018, 6:40 AM
Andreas
Andreas - avatar
0
Thanks Andreas. it worked! 😁 Also, I never came across the ".text" and ".match" validation attributes when I went through the JavaScript script course here. However, I checked the link you gave and found that there are much to learn. Thanks very much. 🙂
15th Nov 2018, 8:49 AM
Nolan
Nolan - avatar