javascriptregexng-pattern

Regex for a number which can starts with 0


I use this regex for my field:

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

What I want to do is to allow the user to enter 0 as a beginning of the number, but in this cas, he must enter at least a second digit diffrent from 0 and the same rule is applied for the third and fourth digits.

Example:

In short, zero value must not be allowed. How can I do this using Regex? or would it be better if I just do it with a javascript script?


Solution

  • If you want to only match numbers that have 1 to 4 digits in the part before a decimal separator, and up to 2 digits after the decimal separator (I deduce it from the regex you used) and that do not start with 00 (that requirement comes from your verbal explanation), use

    /^(?!00)(?!0+(?:[.,]0+)?$)\d{1,~4}(?:[.,]\d{1,2})?$/
    

    See the regex demo.

    Details

    JS demo:

    var ss = ['1','1.1','01','01.3','023.45','0','00','0.0','0.00','0001'];
    var rx = /^(?!00)(?!0+(?:[.,]0+)?$)\d{1,4}(?:[.,]\d{1,2})?$/;
    for (var s of ss) {
     var result = rx.test(s);
     console.log(s, "=>", result);
    }