'Using v7 react-hook-form with v5 mui date pickers

In the react-hook-form documentation you can find a fully working example ( https://codesandbox.io/s/react-hook-form-v7-controller-5h1q5?file=/src/Mui.js ) that uses the KeyboardDatePicker

Now the KeyboardDatePicker is no more available in mui distribution. I tried to integrate the DatePicker (5.0.0-alpha.2 version)

import { useForm, Controller } from "react-hook-form";
import Container from '@mui/material/Container';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';

export default function TryFormAndPicker() {
  const { control, handleSubmit, formState: { errors } } =  useForm({
    defaultValues: { 
      muiDatepicker_v5: null,
    }
  });
  const onSubmit = data => {
    console.log("data",data)
  }
  return (
    <Container component="main" maxWidth="xs">
      <form onSubmit={handleSubmit(onSubmit)}>
        <Controller
          control={control}
          name='muiDatepicker_v5'
          render={({ field: { ref, ...rest } }) => ( 
            <DatePicker
              {...rest}
              label="Date field"
              renderInput={(params) => <TextField margin="dense" {...params} />}
            />
          )}
          rules={{ required: true }}
        />
        {errors.muiDatepicker_v5 && <div className="badValue">{errors.muiDatepicker_v5.type}</div>}
        <Button fullWidth type="submit">Submit</Button>
      </form>
    </Container>
  )
} 

It works in many cases: you get the required error if you don't fill the field, you get the value inserted in the onSubmit function.

But it doesn't work if you insert a bad date (i.e. 33/01/2022): clicking on the submit button, validation is not blocking the submit and onSubmit function is called (muiDatepicker_v5 is NaN)

Even worse if you insert a correct date that is not in the right range (minDate - maxDate): clicking on the submit button, validation is not blocking the submit and onSubmit function is called receiving the inserted date without any change to know that the date is wrong

Any suggestion on how to get it working? Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source