简体   繁体   English

使用正则表达式进行表单验证

[英]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. 1它引发我的警报。 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. 我不太清楚发生这种情况,因为我正在使用onkeydown事件来激活评估功能。 Since consoleLog show me that the value 100 is parsed as 10, 1000 as 100. 由于consoleLog告诉我值100被解析为10,1000被解析为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. 如果更改它们,以便现在使用onkeyup,计算器功能将向我显示值100解析为10,1000解析为100。但是,如果该字段为空,则由于警告框不断弹出,该表单将变得无用。 Evaluation works though if you get a chance to type anything in. 尽管您有机会输入任何内容,但评估仍然有效。

I will now post my code HTML first and JS after 我现在将代码HTML首先发布,然后将JS发布

<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? 问题A:我的评估功能是否有问题导致这种情况发生?

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? 问题B:如果它与事件处理程序有关,该如何解决它,以便在两个函数上都获得onkeyup的效果?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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