I'm working on a registration form made with yup, react-hook-form and Material UI DatePicker/TextField. I'd like to have a date of birth field that checks if the user is above 18 years old. The error message is displayed correcly but the red color of the error state works only if the input is empty (and not when the age is below 18). I'm console logging the value of "invalid" that dictates the red color, and it is set to true when it should.
Here is a sandbox link: =/src/App.js
I'm working on a registration form made with yup, react-hook-form and Material UI DatePicker/TextField. I'd like to have a date of birth field that checks if the user is above 18 years old. The error message is displayed correcly but the red color of the error state works only if the input is empty (and not when the age is below 18). I'm console logging the value of "invalid" that dictates the red color, and it is set to true when it should.
Here is a sandbox link: https://codesandbox.io/s/datepicker-yup-validation-8rod3?file=/src/App.js
Share Improve this question edited May 30, 2023 at 13:28 Olivier Tassinari 8,6814 gold badges25 silver badges26 bronze badges asked Jan 8, 2022 at 16:49 WoXuSWoXuS 1451 gold badge3 silver badges8 bronze badges 2- your sandbox is empty – Saeed Shamloo Commented Jan 9, 2022 at 4:53
- @SaeedShamloo Dunno how that happened, sorry. It's back up now. – WoXuS Commented Jan 9, 2022 at 13:13
2 Answers
Reset to default 10You need to just put error
attribute after {...params}
like this:
<DatePicker
...
renderInput={(params) => (
<TextField
helperText={invalid ? error.message : null}
id="dateOfBirth"
variant="standard"
margin="dense"
fullWidth
color="primary"
autoComplete="bday"
{...params}
error={invalid}
/>
)}
/>
If you are using DatePicker V6, these solutions do not currently work. In the new version, renderInput has been replaced by slotProps. Please check the code of the link.