简体   繁体   中英

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;
}

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM