[英]Form validation in JAvascript with Regexp
我有一個帶有輸入字段的網頁,其中只允許輸入數字。 輸入字段具有一個onkeyup事件,該事件啟動此驗證功能:
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";
}
}
一切正常,直到我按下Backspace按鈕刪除一些字符。 在這種情況下,功能始終表現得就像我輸入字母一樣。
如何糾正呢?
如果測試成功通過,該函數不會返回背景色。
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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.