Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

2.4K
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda