1

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:

  • 01 -> valid
  • 00 -> not valid
  • 0 -> not valid
  • 1 -> valid

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?

Anna
  • 839
  • 2
  • 17
  • 33

2 Answers2

1

Try combining JS and RegEx:

if (parseInt(value) != 0 && value.test(/\d+([,.]\d{1,2})?/)) {
    //valid
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
1

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

  • ^- start of string
  • (?!00) - no two 0s at the start of the string
  • (?!0+(?:[.,]0+)?$) - a negative lookahead that fails the match if there are one or more 0s, followed with an optional sequence of . or , followed with one or more zeros up to the string end
  • \d{1,4} - any 1 to 4 digits
  • (?:[.,]\d{1,2})? - 1 or 0 occurrences of
    • [.,] - a . or ,
    • \d{1,2} - any 1 or 2 digits
  • $ - end of string.

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);
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Note I added a `0001` test case that I guess should fail. Thus, I added a `(?!00)` lookahead to make sure the numbers starting with `00` will get failed. – Wiktor Stribiżew Aug 23 '17 at 08:24
  • @DucFilan Then you have not clicked *Run code snippet*. Or you have not understood the question. – Wiktor Stribiżew Aug 23 '17 at 08:31
  • 1
    @DucFilan then you clearly see it works as per OP expectations: 1) no `00` at the start, 2) the number cannot equal `0`, 3) 1 to 3 digits before decimal separator and 2 digits after. Bro. – Wiktor Stribiżew Aug 23 '17 at 08:36