Reputation: 1055
I am building a form with Yup, React Hook Form and, MUI V5. I am using a DateTimePicker
from MUI V5 but it is not displaying Yup's error messages as expected.
Ideally, the errors should display as follow:
So, if the field is empty and I press the submit button, the invalid format message is displayed.
here is the schemas code:
const schema = yup.object().shape({
name: yup
.string()
.required("Please enter your name. The field cannot be left blank."),
date: yup
.date()
.transform(parseDateString)
.typeError("Invalid date format. (mm/dd/yyyy hh:mm am or pm)")
.nullable()
.required("Please enter a valid date. The field cannot be left blank.")
});
I have tried moving nullable()
to every different position and the result still the same.
I have commented nullable()
and typeError
and I get the default error from date (date must be a date
type, but the final value was: Invalid Date
.)
Upvotes: 3
Views: 3908
Reputation: 1592
add under LocalizationProvider:
{error ? <div className="error">{error}</div> : null}
Upvotes: 0
Reputation: 1095
The Invalid Date
error comes from the date-fns
parser function that is in the parseDateString
function called in the Yup transform method.
Yup transform method is used to transform incoming date from the input field, in this case it's MUI's DateTimePicker.
That being sad it has nothing to do with this error and the problem is in the DatePicker
component. Make note of the TextField
and {...params}
destructuring. Since the error prop was before we destructure params it was overwritten.
const CalPicker = ({ helperText, name, label, control, required, error }) => {
const [value, setValue] = React.useState();
return (
<Stack sx={{ mt: 2 }}>
<LocalizationProvider dateAdapter={DateAdapter}>
<Controller
name={name}
control={control}
render={({ field }) => (
<DateTimePicker
{...field}
renderInput={(params) => (
<TextField
required={required}
{...params}
helperText={helperText}
error={error}
/>
)}
label={label}
value={value}
onChange={(newValue) => {
field.onChange(newValue);
setValue(newValue);
}}
/>
)}
/>
</LocalizationProvider>
</Stack>
);
};
Upvotes: 0