Form validation in JAvascript with Regexp
I have a开发者_JAVA技巧 webpage with an input field where only digits are allowed. The input field has an onkeyup event that starts this validating function:
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";
}
}
Everything works as I expect until I hit Backspace button to remove some characters. In this case function always behaves as if I entered letters.
How to correct this?
The function don't put back the background color if the test is passed sucessfully.
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";
}
}
精彩评论