Search code examples
javascriptreactjsmaterial-uireact-hook-formyup

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


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


Solution

  • 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}
        />
      )}
    />