Validate negative and positive decimal numbers with RegEx

后端 未结 5 880
滥情空心
滥情空心 2020-12-09 23:39

I am trying to build a regex which will allow both negative and positive decimal numbers with the following rules.

  1. there can not be more than 2 digits after de
相关标签:
5条回答
  • 2020-12-09 23:53

    It is pretty straightforward since 12 - 9 == 3 for two decimals + the dot.

    var re = new RegExp('^-?\\d{1,9}(\\.\\d{1,2})?$');
    

    authorizes

    • -123456789
    • -123456789.1
    • -123456789.12
    • 0
    • 0.12

    but will not accept

    • 01234567890123 more than 12 decs
    • 123. a dot without decimals
    • 123.123 more than two decimals
    • . or .12 (missing 0)
    0 讨论(0)
  • 2020-12-09 23:55

    My own regex:

    var rgx = /^(-{1}?(?:([0-9]{0,10}))|([0-9]{1})?(?:([0-9]{0,9})))?(?:\.([0-9]{0,3}))?$/;
    
    0 讨论(0)
  • 2020-12-10 00:02
    var NumberToValidate = 48428;
            var valid =  /^([0-9]*[1-9][0-9]*)$/.test(NumberToValidate);
            {
            if (!valid)
        alert("Invalid Quantity!!\nThe Quantity cannot be Zero\n or a part of a Unit !");
                return false;
            }
    
    0 讨论(0)
  • 2020-12-10 00:09

    Check this regex.

    ^[+-]?[0-9]{1,9}(?:\.[0-9]{1,2})?$
    

    This regex says

    • sign is optional
    • at least one and max 9 digits as integer part
    • if decimal point is there, at least one and max two digits after it.
    0 讨论(0)
  • 2020-12-10 00:16

    /(?:^(?:(?:[1-9][0-9]{1,})|0)\.[0-9]{1,}$)|^[1-9]+[0-9]*$/
    
    0 讨论(0)
提交回复
热议问题