Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

2.4K
Views
Using the MUI 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 MUI 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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

this solution was wrote with formik , yup and material datepicker :

    import "./styles.css";
import LocalizationProvider from "@mui/lab/LocalizationProvider";
import AdapterDateFns from "@mui/lab/AdapterDateFns";
import DateTimePicker from "@mui/lab/DateTimePicker";
import * as Yup from "yup";
import { useFormik } from "formik";
import { Button, TextField } from "@mui/material";
import moment from "moment";
var y = new Date();
y.setFullYear(y.getFullYear() - 18);

const validationSchema = Yup.object().shape({
  voyageNumber: Yup.number(),
  voyageStartDate: Yup.date(),
  voyageEndDate: Yup.date().when("voyageStartDate", (voyageStartDate, schema) =>
    moment(voyageStartDate).isValid() ? schema.max(voyageStartDate) : schema
  )
});
export default function App() {
  const formik = useFormik({
    initialValues: {
      voyageStartDate: moment().add(-18, "years"),
      voyageEndDate: null
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      console.log(values);
    }
  });
  return (
    <div className="App">
      <form autoComplete="off">
        <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DateTimePicker
            renderInput={(props) => (
              <TextField
                variant="standard"
                className="w-100"
                name="voyageEndDate"
                required
                {...props}
                error={
                  formik.touched?.voyageEndDate &&
                  !!formik.errors?.voyageEndDate
                }
                helperText={
                  formik.touched?.voyageEndDate && formik.errors?.voyageEndDate
                }
              />
            )}
            name="voyageEndDate"
            label="Voyage End"
            value={formik.values?.voyageEndDate}
            onChange={(newValue) => {
              console.log(
                moment(newValue).format("YYYY-MM-DD HH:mm:ss"),
                moment(y).format("YYYY-MM-DD HH:mm:ss"),
                formik.errors
              );
              formik.setFieldTouched("voyageEndDate");
              formik.setFieldValue(
                "voyageEndDate",
                moment(newValue).format("YYYY-MM-DD HH:mm:ss")
              );
            }}
            onKeyPress={() => formik.setFieldTouched("voyageEndDate")}
          />
        </LocalizationProvider>
        <div style={{ marginTop: "15px" }}>
          <Button variant="contained" color="primary" type="submit">
            Add Voyage
          </Button>
        </div>
      </form>
    </div>
  );
}

sandbox link

over 4 years ago · Santiago Trujillo Report

0

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}
    />
  )}
/>
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!