Home > front end >  Javascript Decimal Place Restriction To Specific Number With Regex
Javascript Decimal Place Restriction To Specific Number With Regex

Time:11-12

I have some client-side validation against a input type number which

  • Will accept any number 0 through 99 with 2 decimal places
  • And the values of the decimals must be .00, .25, .33, .5, .67, .75

I've tried with 2 digit length validation but how can I validate specific list of decimal numbers with regex ?

/^\d{1,2}(\.\d{1,2})?$/

VALID CASES

5.25

78.5

99.75

INVALID CASES

88.12

50.78

CodePudding user response:

You could write the pattern as:

^\d{1,2}\.(?:00|[72]5|33|67|50?)$

Explanation

  • ^ Start of string
  • \d{1,2} Match 1 or 2 digits
  • \. Match a dot
  • (?: Non capture group for the alternatives
    • 00|[72]5|33|67|50? match 00 75 25 33 67 5 or 50
  • ) Close the non capture group
  • $ End of string

Regex demo

CodePudding user response:

I would use an alternation for the various allowed decimal endings:

^\d{1,2}\.(?:00|25|33|5|67|75)$

CodePudding user response:

I am not clear if you allow leading zeros. Here is a solution if not:

const regex = /^(?:\d|[1-9]\d)\.(?:00|25|33|5|67|75)$/;
[
  '0.33',
  '5.25',
  '78.5',
  '99.75',
  '09.75',
  '88.12',
  '50.78'
].forEach(str => {
  console.log(str   ' => '   regex.test(str));
});

Output:

0.33 => true
5.25 => true
78.5 => true
99.75 => true
09.75 => false
88.12 => false
50.78 => false

Explanation of regex:

  • ^ -- anchor at start of string
  • (?:\d|[1-9]\d) -- non-capture group: either a single digit, or two digits 10...99
  • \. -- literal dot
  • (?:00|25|33|5|67|75) -- non-capture group: local or of allowed decimals
  • $ -- anchor at end of string
  • Related