Carlos
Carlos

Reputation: 119

Regex: integer OR decimal OR fraction

In JavaScript, would it possible to validate if some input is an integer OR a decimal (using dots or commas as separator) OR a fraction (without allowing zeros in the numerator or the denominator) with a single regex?

Examples of valid inputs:

1
2
1.5
2,5
111.422
0,5
1/2
3/4

etc.

Invalid inputs

00,5
00.5
0/1
1/0

etc.

So far I'm using this for the decimal part:

^(0|[1-9]\d*)([\.,]\d*)?$

but I'm having trouble combining it with the fraction part. I don't know if it would be even possible with only one regex without using some extra flow control.

Thanks!

Upvotes: 0

Views: 328

Answers (2)

Mitya
Mitya

Reputation: 34556

I think this is robust:

/^(0?([1-9][0-9]*)?([\.,])?0?([1-9][0-9]*)?|[1-9]+\/[1-9]+)$/

Example:

let foo = [
    '1',
    '2',
    '1.5',
    '2,5',
    '111.422',
    '0,5',
    '1/2',
    '3/4',
    '00,5',
    '00.5',
    '0/1',
    '1/0'
];
foo.forEach(val => {
    console.log(val, /^(0?([1-9][0-9]*)?([\.,])?0?([1-9][0-9]*)?|[1-9]+\/[1-9]+)$/.test(val));
});

Gives

1 true
2 true
1.5 true
2,5 true
111.422 true
0,5 true
1/2 true
3/4 true
00,5 false
00.5 false
0/1 false
1/0 false

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163257

You could add an alternation where both the numerator or the denominator start with a digit 1-9

If for example 3. is also not valid, you can repeat the digits 1+ times in this part (?:[.,]\d+)?

Note that you don't have to escape the dot in the character class.

^(?:(?:0|[1-9]\d*)(?:[.,]\d+)?|[1-9]\d*\/[1-9]\d*)$

Regex demo

let pattern = /^(?:(?:0|[1-9]\d*)(?:[.,]\d+)?|[1-9]\d*\/[1-9]\d*)$/;
["1",
  "2",
  "1.5",
  "2,5",
  "111.422",
  "0,5",
  "1/2",
  "3/4",
  "00,5",
  "00.5",
  "0/1",
  "1/0"
].forEach(s => console.log(`${s} --> ${pattern.test(s)}`))

Upvotes: 2

Related Questions