Validating a text field containing a float is a valid percentage value?

后端 未结 3 1325
北海茫月
北海茫月 2021-01-29 05:00

I have a form text field that has a KeyUp event. On KeyUp I\'m ignoring anthing but numbers, the period, backspace, delete and cursor keys. So, the only thing in the field ca

3条回答
  •  广开言路
    2021-01-29 05:40

    Some people will suggest regexes, but I think a small function is better suited for such a validation:

    function validate(x) {
        var parts = x.split(".");
        if (typeof parts[1] == "string" && (parts[1].length == 0 || parts[1].length > 2))
            return false;
        var n = parseFloat(x);
        if (isNaN(n))
            return false;
        if (n < 0 || n > 100)
            return false;
    
        return true;
    }
    
    console.log(validate("95"));
    console.log(validate("95."));
    console.log(validate("95.0"));
    console.log(validate("95.00"));
    console.log(validate("95.000"));
    console.log(validate("101.01"));
    console.log(validate("101"));
    

    Live example

提交回复
热议问题