1

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;
}
5
  • 2
    Just use <input type="number"> and the user won't be able to enter anything but numbers. Commented Nov 21, 2019 at 22:53
  • @ScottMarcus Okay, but out of curiousity,how would it work with javascript? Commented Nov 21, 2019 at 22:54
  • Number.isNaN only checks to see if the passed value is ===NaN not if something cant be converted to a number. You probably meant to use the global isNaN Commented Nov 21, 2019 at 23:03
  • 1
    what does number.constructor; do? Commented Nov 21, 2019 at 23:03
  • stackoverflow.com/questions/9716468/… Commented Nov 22, 2019 at 0:15

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

really really sleek

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.