I am trying to block the user to enter invalid numbers. I am currently supporting the years from 1901
to 20XX
. So for example when the user is trying to enter the year from either 2 or 1 should be fine in the first letter but not 3. In the second character, a user can enter 9 or 0 and they shouldn't enter 3 or 4, etc. this is my current implementation but it's blocking from the first character because it's checking for the entire string at once.
<TextField
fullWidth
sx={{ pr: 3 }}
value={dateOfBirth}
{...params}
onInput={(e) => {
const regex =
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;
console.log(e.target.value);
e.target.value = regex.test(e.target.value)
? e.target.value
: "";
}}
/>