使用Regexp在JAvascript中进行表单验证
我有一个只允许数字输入的网页。 输入字段具有启动此验证功能的onkeyup事件:使用Regexp在JAvascript中进行表单验证,javascript,regex,forms,Javascript,Regex,Forms,我有一个只允许数字输入的网页。 输入字段具有启动此验证功能的onkeyup事件: function validate() { var uah_amount = document.getElementById("UAH").value; var allowed = /^\d+$/; document.getElementById("error").innerHTML = document.getElementById("UAH").value; if (!allo
function validate() {
var uah_amount = document.getElementById("UAH").value;
var allowed = /^\d+$/;
document.getElementById("error").innerHTML = document.getElementById("UAH").value;
if (!allowed.test(uah_amount)) {
document.getElementById("error").style.backgroundColor = "red";
}
}
在我点击退格按钮删除一些字符之前,一切都按照我的预期进行。在这种情况下,函数的行为就像我输入字母一样
如何更正此问题?如果测试成功通过,函数不会恢复背景色。
function validate() {
var uah_amount = document.getElementById("UAH").value-0;
var allowed = /^\d+$/;
document.getElementById("error").innerHTML = document.getElementById("UAH").value;
if (!allowed.test(uah_amount)) {
document.getElementById("error").style.backgroundColor = "red";
} else {
document.getElementById("error").style.backgroundColor = "transparent";
}
}
函数验证(){
var uah_amount=document.getElementById(“uah”).value-0;
允许的变量=/^\d+$/;
document.getElementById(“错误”).innerHTML=document.getElementById(“UAH”).value
如果(!允许测试(乌克兰格里夫纳金额)){
document.getElementById(“错误”).style.backgroundColor=“红色”;
}否则{
document.getElementById(“错误”).style.backgroundColor=“透明”;
}
}
对我来说似乎效果不错(需要时重写一点,将其改回白色):