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 alternatives00|[72]5|33|67|50?
match00
75
25
33
67
5
or50
)
Close the non capture group$
End of string
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: localor
of allowed decimals$
-- anchor at end of string