Getting "TypeError date.isBefore is not a function" while using material ui date-picker with formik

huangapple go评论68阅读模式
英文:

Getting "TypeError date.isBefore is not a function" while using material ui date-picker with formik

问题

I understand that you want me to translate the code part and exclude other content. Here's the translated code:

import React from "react";
import { Formik } from "formik";
import { Box, Button, Paper, Stack, TextField, styled } from "@mui/material";
import { Lock } from "@mui/icons-material";
import * as yup from "yup";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";

const LoginPage = () => {
  const StyledPaper = styled(Paper)({
    width: "500px",
    borderRadius: "10px",
    backgroundColor: "white",
    padding: "30px",
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)"
  });

  //----VALIDATION-----//

  const userSchema = yup.object().shape({
    userName: yup.string().required("required"),
    dob: yup.date().required("required")
  });

  const handleFormSubmit = (values, onSubmitProps) => {
    console.log(values);
  };

  return (
    <Formik
      onSubmit={handleFormSubmit}
      initialValues={{ userName: "", dob: new Date() }}
      validationSchema={userSchema}
    >
      {({
        values,
        errors,
        touched,
        handleBlur,
        handleChange,
        handleSubmit,
        resetForm
      }) => (
        <form onSubmit={handleSubmit}>
          <StyledPaper elevation={3}>
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                margin: "10px"
              }}
            >
              <Lock color="primary" fontSize="large" />
            </Box>
            <Stack direction="column" gap={2}>
              <TextField
                label="User Name"
                value={values.userName}
                onChange={handleChange}
                onBlur={handleBlur}
                name="userName"
                error={Boolean(touched.userName) && Boolean(errors.userName)}
                helperText={touched.userName && errors.userName}
              />

              <LocalizationProvider dateAdapter={AdapterDayjs}>
                <DatePicker
                  label="Date of birth"
                  value={values.dob}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  name="dob"
                  error={Boolean(touched.dob) && Boolean(errors.dob)}
                  helperText={touched.dob && errors.dob}
                />
              </LocalizationProvider>

              <Button variant="contained" type="submit">
                Submit
              </Button>
            </Stack>
          </StyledPaper>
        </form>
      )}
    </Formik>
  );
};

export default LoginPage;

Please note that I've translated the code part as requested, and you can use it for reference.

英文:

Getting "TypeError date.isBefore is not a function" while using material ui date-picker with formik.Can you help me where I am going wrong. I want to get value of dob field in values object of formik.

==========================================================================
My attempt:

import React from &quot;react&quot;;
import { Formik } from &quot;formik&quot;;
import { Box, Button, Paper, Stack, TextField, styled } from &quot;@mui/material&quot;;
import { Lock } from &quot;@mui/icons-material&quot;;
import * as yup from &quot;yup&quot;;
import { AdapterDayjs } from &quot;@mui/x-date-pickers/AdapterDayjs&quot;;
import { LocalizationProvider } from &quot;@mui/x-date-pickers/LocalizationProvider&quot;;
import { DatePicker } from &quot;@mui/x-date-pickers/DatePicker&quot;;
// import dayjs from &#39;dayjs&#39;;
const LoginPage = () =&gt; {
const StyledPaper = styled(Paper)({
width: &quot;500px&quot;,
borderRadius: &quot;10px&quot;,
backgroundColor: &quot;white&quot;,
padding: &quot;30px&quot;,
position: &quot;absolute&quot;,
top: &quot;50%&quot;,
left: &quot;50%&quot;,
transform: &quot;translate(-50%, -50%)&quot;
});
//----VALIDATION-----//
const userSchema = yup.object().shape({
userName: yup.string().required(&quot;required&quot;),
dob: yup.date().required(&quot;required&quot;)
});
const handleFormSubmit = (values, onSubmitProps) =&gt; {
console.log(values);
};
return (
&lt;Formik
onSubmit={handleFormSubmit}
initialValues={{ userName: &quot;&quot;, dob: new Date() }}
validationSchema={userSchema}
&gt;
{({
values,
errors,
touched,
handleBlur,
handleChange,
handleSubmit,
resetForm
}) =&gt; (
&lt;form onSubmit={handleSubmit}&gt;
&lt;StyledPaper elevation={3}&gt;
&lt;Box
sx={{
display: &quot;flex&quot;,
justifyContent: &quot;center&quot;,
alignItems: &quot;center&quot;,
margin: &quot;10px&quot;
}}
&gt;
&lt;Lock color=&quot;primary&quot; fontSize=&quot;large&quot; /&gt;
&lt;/Box&gt;
&lt;Stack direction=&quot;column&quot; gap={2}&gt;
&lt;TextField
label=&quot;User Name&quot;
value={values.userName}
onChange={handleChange}
onBlur={handleBlur}
name=&quot;userName&quot;
error={Boolean(touched.userName) &amp;&amp; Boolean(errors.userName)}
helperText={touched.userName &amp;&amp; errors.userName}
/&gt;
&lt;LocalizationProvider dateAdapter={AdapterDayjs}&gt;
&lt;DatePicker
label=&quot;Date of birth&quot;
value={values.dob}
onChange={handleChange}
onBlur={handleBlur}
name=&quot;dob&quot;
error={Boolean(touched.dob) &amp;&amp; Boolean(errors.dob)}
helperText={touched.dob &amp;&amp; errors.dob}
/&gt;
&lt;/LocalizationProvider&gt;
&lt;Button variant=&quot;contained&quot; type=&quot;submit&quot;&gt;
Submit
&lt;/Button&gt;
&lt;/Stack&gt;
&lt;/StyledPaper&gt;
&lt;/form&gt;
)}
&lt;/Formik&gt;
);
};
export default LoginPage;

=========================================================================================

Please find below the sandbox link-

text

答案1

得分: 11

DatePicker 需要使用 dayjs 来修复:

  1. 从你的代码中取消注释 dayjs 的导入部分
  2. 更改 DatePicker 的 value 属性
import dayjs from 'dayjs';

<DatePicker
  label="出生日期"
  value={dayjs(values.dob)}
  onChange={handleChange}
  onBlur={handleBlur}
  name="dob"
  error={Boolean(touched.dob) && Boolean(errors.dob)}
  helperText={touched.dob && errors.dob}
/>
英文:

DatePicker is expecting dayjs, to fix:

  1. Uncomment the dayjs import from your code and

  2. Change the value prop for DatePicker

     import dayjs from &#39;dayjs&#39;;
    &lt;DatePicker
    label=&quot;Date of birth&quot;
    value={dayjs(values.dob)}
    onChange={handleChange}
    onBlur={handleBlur}
    name=&quot;dob&quot;
    error={Boolean(touched.dob) &amp;&amp; Boolean(errors.dob)}
    helperText={touched.dob &amp;&amp; errors.dob}
    /&gt;
    

huangapple
  • 本文由 发表于 2023年4月17日 20:22:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定