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

后端 未结 3 1324
北海茫月
北海茫月 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

    0 讨论(0)
  • 2021-01-29 05:48

    You could limit the length of your field to 5, check that the value can be cast to a number, and then verify that the number is between 0 and 100. You won't be able to enter 100.00, but why would you need to?

    Also, here's a fiddle for testing. One note, if you really care about validating "95." as false, you'll have to add extra validation for that. However, I'd advise against this requirement, because it is still represents a valid percentage and won't affect the outcome of calculations.

    0 讨论(0)
  • 2021-01-29 05:51

    try this expression: the 100% is a special case of a more generic pattern

    var re = /^((0|[1-9]\d?)(\.\d{1,2})?|100(\.00?)?)$/;
    

    explanation

    (0|[1-9]\d?) allows numbers from 0 to 99

    (\.\d{1,2})? allows a dot with 1 or 2 digits after

    | otherwise

    100 accept 100

    (\.00?)? with optional 0 or 00

    Edit:

    I tried this jsfiddle demo http://jsfiddle.net/pCDVn/1/ and it's working... look at the console

    0 讨论(0)
提交回复
热议问题