简体   繁体   中英

form validation with regular expression

Im working on a script which takes a form input and calculates a total including VAT. I am attempting to validate the user input making sure he&she only uses whole numbers.

My problem is that when I type in the first number ie. 1 it throws my alert. And when continuing to add numbers it works fine. When typing in letters it works as supposed and return the alert.

I have a faint idea that this happens because I am using onkeydown event for activating the evaluation function. Since consoleLog show me that the value 100 is parsed as 10, 1000 as 100.

If I change them around so I now use onkeyup the calculator function will show me that the value 100 is parsed as 10, 1000 as 100. But if the field is empty the form is rendered unuseless because of the alert box keeps popping up. Evaluation works though if you get a chance to type anything in.

I will now post my code HTML first and JS after

<input type="text" id="price" name="price" onkeyup="checkIfWholeNo();" onkeydown="calculate();" />

function checkIfWholeNo() {
var price = document.getElementById('price').value;
if(/^\d+$/.test(parseInt(price))){}
else {alert("not a number"); return false;}
}
}

Question A: Is there something wrong with my evaluation function that makes this happen?

Question B: If it has to do with the event handlers how do I fix it so I get the effect of onkeyup on both the functions?

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