I have this component called hours, an input field where the user can either type the hours or click an arrow on over or on click (up or down):
<SquareInput
type="number"
pattern="\d*"
min="0"
step="1"
onChange={(e) => {
const value = e.target.value;
const updatedValue = regexHours.test(value)
if (updatedValue > 24 || updatedValue < 0) {
return;
} else {
setHours(value);
}
}}
value={hours}
/>
I want to let the user type:
But in this current way the user can type 4 digits and symbols as well, I was thinking that maybe a regex would solve the problem such as: const regexHours = '/^((?:[1-9]|1[0-9]|2[0-4])(?:.d{1,2})?|25(?:.00?)?)$)/'; But I have no clue how to implement it and if it is the right approach. All the things I tried by using SO gave me errors.
While for the Minutes component:
<SquareInput value={minutesDuration} />
I will the have same issues but instead I want to show:
And I found this regex: const regexMinutes = '[0-9]|[1-5][0-9]';
Any ideas how to tackle the problem? currently I get SyntaxError: unmatched ) in regular expression To give a better idea how the components look like here below you will find a screenshot:
You can use a regular expression like this:
const reHours = /^[0-1][0-9]$|^2[0-4]$/
console.log(reHours.test('12'))
console.log(reHours.test('19'))
console.log(reHours.test('05'))
console.log(reHours.test('22'))
console.log(reHours.test('29'))
console.log(reHours.test('34'))
console.log(reHours.test('1a2'))
console.log(reHours.test('b12'))
console.log(reHours.test('q12'))
console.log(reHours.test('12@'))
console.log(reHours.test('1'))
const reMinutes = /^[0-5][0-9]$/
<SquareInput
type="number"
pattern="\d*"
min="0"
step="1"
onChange={(e) => regexHours.test(e.target.value) ? e.target.value : ""}
value={hours}
/>