Javascript - validation, numbers only

2020-02-02 12:04发布

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?

Part of the Login

<form name="myForm">
    <label for="firstname">Age: </label>
    <input name="num" type="text" id="username" size="1">
    <input type="submit" value="Login" onclick="return validateForm()">

function validateForm()
{

    var z = document.forms["myForm"]["num"].value;
    if(!z.match(/^\d+/))
        {
        alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
        }
}

13条回答
神经病院院长
2楼-- · 2020-02-02 12:32
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
   elem[i].addEventListener('keypress', function(event){
      var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
      var validIndex = keys.indexOf(event.charCode);
      if(validIndex == -1){
         event.preventDefault();
      }
  });
}
查看更多
登录 后发表回答