PJ445
PJ445

Reputation: 23

Validate a number input with javascript

I am trying to validate my form information using javascript. My form has an amount value that must be entered as a number. I am trying to make it so a number must be inputted but I cannot quite get down the issue I am having with my javascript function

<form name="formname" onsubmit="return checkNumInput()" action="nextpage.php" method="post">

function checkNumInput(){
    number.constructor;
    var amount = document.forms["formname"]["amount"];
    if(Number.isNaN(amount.value)){
        window.alert("amount must be a number");
        amount.focus();
        return false;
    }
    return true;
}

Upvotes: 1

Views: 52

Answers (1)

qelli
qelli

Reputation: 2077

If you ain't planning to use native HTML5 number input, with JavaScript is as easy as this:

const input = document.querySelector("#numbers");

input.addEventListener("keydown", verifyKey);

function verifyKey(e) {
  if(isNaN(+e.key) && e.key!="Backspace"){
    e.preventDefault();
  }
}
<input type="text" id="numbers">

Upvotes: 2

Related Questions