Search code examples
javascriptregexvalidationnumbers

Regular expression for double number range validation


I look for a regular expression to support double number with just one fraction part which ranges between 0.1 to 999.9

It means following values are not allowed:

0
0.0 // less than lower bound
0.19 // fraction part is 2 digits, right '9' is extra
94.11 // fraction part is 2 digits, right '1' is extra
999.90 // fraction part is 2 digits, '0' is extra
9.0 // should be 9 or 9.1, 9.0 is wrong
1000 // is higher than upper bound

allowed ones:

1.1
55.5
999.9

My regular expression is:

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

Which doesn't support 0.1 to 0.9 and extra zeros like 99.000 and 99.0

Test steps: In your browser console:

var reg = new RegExp(/(^(\.[1-9])?$|(^[1-9][0-9]{0,2}?(\.[1-9])?$))$/);
reg.test(12);

Any help appriciated


Solution

  • I guess this is the most accurate:

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

    Note that you don't need the RegExp constructor when working with regex literals:

     re = /^(0\.[1-9]|[1-9][0-9]{0,2}(\.[1-9])?)$/
     a = [0, 0.1, 123, 123.4, '00.1', 123.45, 123456, 'foo']
     a.map(function(x) { console.log(x, re.test(x)) })
    

    0 false
    0.1 true
    123 true
    123.4 true
    00.1 false
    123.45 false
    123456 false
    foo false