开发者

Form validation in JAvascript with Regexp

开发者 https://www.devze.com 2022-12-29 13:24 出处:网络
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:

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"; } }
0

精彩评论

暂无评论...
验证码 换一张
取 消