最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using the Material UI DatePicker with yup and react-hook-form - the error prop doesn't work as intended - S

programmeradmin0浏览0评论

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
Add a comment  | 

2 Answers 2

Reset to default 10

You 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论