为什么 MUI DatePicker 只传递年份的 1 位数?

Why does MUI DatePicker pass on only 1-digit of the year?

提问人:hanlok 提问时间:11/8/2023 更新时间:11/9/2023 访问量:27

问:

我正在尝试使用 MUI 字段设置注册表单,但日期的输入字段无法正常工作。当我输入日期、日期和月份时,正确传递,但当涉及到年份时,它只传递输入的数字。例如,当我输入 08.11.2023 时,它只通过了 08.11.3。我发现,当我在例如月份中编辑其他数字之一时,它会完成到 2023 年的一年。通过日期选取器表选择日期也不起作用。

变量:

  const [dob, setDOB] = useState("");
  const [validDOB, setValidDOB] = useState(false);
  const [DOBFocus, setDOBFocus] = useState(false);

  useEffect(() => {
    const today = new Date();
    const age = differenceInYears(today, dob);
    const result = DOB_REGEX.test(age);
    setValidDOB(result);
  }, [dob]);

更改功能:

  function handleChange(event) {

    setFormData((prevFormData) => {
      return {
        ...prevFormData,
        [event.target.name]: event.target.value,
      };
    });
  }

表单数据:

  const handleSubmit = async (e) => {
    e.preventDefault();
    const v1 = FIRSTNAME_REGEX.test(firstname);
    const v2 = PWD_REGEX.test(password);
    const v3 = LASTNAME_REGEX.test(lastname);
    const v5 = STREET_REGEX.test(street);
    const v6 = NUMBER_REGEX.test(housenumber);
    const v7 = PLZ_REGEX.test(plz);
    const v8 = PID_REGEX.test(pid);
    const v9 = MAIL_REGEX.test(email);
    if (!v1 || !v2 || !v3 || !v5 || !v6 || !v7 || !v8 || !v9) {
      setErrMsg("Invalid input");
      return;
    }
    setSuccess(true);
     
    try {
      const { data, error } = await supabase.auth.signUp({
        email: formData.email,
        password: formData.password,
        options: {
          data: {
            first_name: formData.firstname,
            last_name: formData.lastname,
            date_of_birth: formData.dob,
            street_form: formData.street,
            house_number: formData.housenumber,
            house_number_add: formData.housenumberadd,
            zip_code: formData.plz,
            city_form: formData.city,
            phone_nr: formData.phonenr,
            passport_ID: formData.pid
          },
        },
      });
      alert("Check your email for the verification link");
    } catch (error) {
      alert(error);
    }
  };

输入字段:

            <FormControl>
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <DemoContainer
                components={['DatePicker']}
                sx={{ m: 1 / 2, width: "59ch" }}
              >
                <DatePicker
                  label="Day of birth"
                  slotProps={{ textField: { name: 'dob', id: 'dob', onInput: handleChange }}}
                  //fullWidth="true"
                  format="DD.MM.YYYY"
                  //required
                  autoFocus
                  //color={validDOB ? "success" : "error"}
                  onChange={(e) => {setDOB(new Date(e))}}
                  inputRef={userRef}
                  onFocus={() => setDOBFocus(true)}
                  onBlur={() => setDOBFocus(false)}
                  helperText={
                    !DOBFocus
                      ? ""
                      : validDOB
                      ? ""
                      : "You must be 18 years old to register."
                  }
                />
              </DemoContainer>
            </LocalizationProvider>
            </FormControl>

我也尝试过这个,效果很好,但在我看来这不是最好的解决方案:

<FormControl sx={{ m: 1 / 2 }}>
              <TextField
                label="Geburtsdatum"
                fullWidth="true"
                type="date"
                name="dob"
                id="dob"
                required
                autoFocus
                color={validDOB ? "success" : "error"}
                onInput={handleChange}
                onChange={(e) => {
                  setDOB(e.target.value);
                }}
                inputRef={userRef}
                onFocus={() => setDOBFocus(true)}
                onBlur={() => setDOBFocus(false)}
                helperText={
                  !DOBFocus
                    ? ""
                    : validDOB
                    ? ""
                    : "You must be 18 years old to register."
                }
              />
            </FormControl>
ReactJS 材料-UI 日期选择器

评论


答:

0赞 kofeigen 11/9/2023 #1

DatePicker 正在使用 AdapterDayjs。DatePicker 的 onChange 处理程序接收 DayJs 对象,而不是日期字符串或本机 JavaScript Date 对象。(以下是 JavaScript Date 构造函数的语法,供参考)。

尝试更改此项:

onChange={(e) => {setDOB(new Date(e))}}

通过将 DayJs 对象转换为日期字符串

onChange={(e) => {setDOB(new Date(e.format( 'YYYY-MM-DD' )))}}

或将 DayJs 对象转换为原生 JavaScript Date 对象

onChange={(e) => {setDOB(new Date(e.toDate()))}}

评论

0赞 hanlok 11/9/2023
不,对不起,这些也没有成功。但我发现了我的错误。
0赞 hanlok 11/9/2023 #2

我发现了我的错误。 我现在正在做的是: 我像以前一样定义了变量。 我删除了handleChange事件,并在handleSubmit函数中定义了formData:

  const handleSubmit = async (e) => {

e.preventDefault();
const v1 = FIRSTNAME_REGEX.test(firstname);
const v2 = PWD_REGEX.test(password);
const v3 = LASTNAME_REGEX.test(lastname);
const v4 = DOB_REGEX.test(dob)
const v5 = STREET_REGEX.test(street);
const v6 = NUMBER_REGEX.test(housenumber); 
const v7 = PLZ_REGEX.test(plz);
const v8 = PID_REGEX.test(pid);
const v9 = MAIL_REGEX.test(email);
const v10 = ((housenumberadd==='')? true : NUMBERADD_REGEX.test(housenumberadd));
if (!v1 || !v2 || !v3 || !v4 || !v5 || !v6 || !v7 || !v8 || !v9 || !v10) {
  setErrMsg("Invalid input");
  return;
}
const formData = {
  firstname: firstname,
  lastname: lastname,
  dob: dob,
  street: street,
  housenumber: housenumber,
  housenumberadd: housenumberadd,
  plz: plz,
  city: city,
  email: email,
  phonenr: phonenr,
  pid: pid,
  password: password,
};
console.log(formData);

setSuccess(true);


try {
  const { data, error } = await supabase.auth.signUp({
    email: formData.email,
    password: formData.password,
    options: {
      data: {
        first_name: formData.firstname,
        last_name: formData.lastname,
        date_of_birth: formData.dob,
        street_form: formData.street,
        house_number: formData.housenumber,
        house_number_add: formData.housenumberadd,
        zip_code: formData.plz,
        city_form: formData.city,
        phone_nr: formData.phonenr,
        passport_ID: formData.pid
      },
    },
  });
  alert("Check your email for the verification link");
} catch (error) {
  alert(error);
}

}; 我将 DatePicker onChange 更改为以下内容:

onChange={(e) => {
                  setDOB(dayjs(e).format("DD.MM.YYYY"));