Formik & Yup:如何验证提供的日期是否为 18 岁?

Formik & Yup: How to validate if the provided date is eighteen years old?

我正在使用 Formik、Yup 和 ReactJS 制作的表单。在日期字段中,我试图验证用户是否年满 18 岁。我在 Formik 中通过了以下作为 validationSchema 参数:

import differenceInYears from "date-fns/differenceInYears";
...
...
...
    dob: Yup.date()
              .nullable()
              .test("dob", "Should be greater than 18", function (value) {
                return differenceInYears(value, new Date()) >= 18;
              }),

formik 输入字段的名称是 dob。但即使我输入 18 岁的有效日期,它也会显示验证错误。那么,如何正确验证呢?

您需要交换日期参数:

differenceInYears(new Date(), new Date(value)) >= 18;

如果勾选date-fns docs,第一个参数应该是较晚的日期。

还需要将字段值解析成Date.

我的解决方案:


import React from "react";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
import s from "./Registration.module.css";

const SignupSchema = Yup.object().shape({
  firstName: Yup.string().required("Required"),
  lastName: Yup.string().required("Required"),
  birthdate: Yup.date()
    .max(new Date(Date.now() - 567648000000), "You must be at least 18 years")
    .required("Required"),
  password: Yup.string()
    .min(4, "Too Short!")
    .max(50, "Too Long!")
    .required("Required"),
  email: Yup.string().email("Invalid email").required("Required"),
});

export const RegistrationForm = () => (
  <div className={s.mainLoginForm}>
    <h1>Sign up</h1>
    <Formik
      initialValues={{
        firstName: "",
        lastName: "",
        email: "",
        password: "",
        birthdate: "",
      }}
      validationSchema={SignupSchema}
      onSubmit={(values) => {
        // same shape as initial values
        console.log(values);
      }}
    >
      {({ errors, touched }) => (
        <Form>
          <div className={s.inputsFlex}>
            <Field
              className={s.regInput}
              placeholder="email"
              name="email"
              type="email"
            />
            {errors.email && touched.email ? (
              <div className={s.formControl}>{errors.email}</div>
            ) : null}
            <Field
              className={s.regInput}
              placeholder="password"
              name="password"
              type="password"
            />
            {errors.password && touched.password ? (
              <div className={s.formControl}>{errors.password}</div>
            ) : null}
            <Field
              className={s.regInput}
              placeholder="firstName"
              name="firstName"
            />
            {errors.firstName && touched.firstName ? (
              <div className={s.formControl}>{errors.firstName}</div>
            ) : null}
            <Field
              className={s.regInput}
              placeholder="lastName"
              name="lastName"
            />
            {errors.lastName && touched.lastName ? (
              <div className={s.formControl}>{errors.lastName}</div>
            ) : null}
            <Field className={s.regInput} name="birthdate" type="date" />
            {errors.birthdate && touched.birthdate ? (
              <div className={s.formControl}>{errors.birthdate}</div>
            ) : null}
            <button className={s.regBtn} type="submit">
              Sign up
            </button>
          </div>
        </Form>
      )}
    </Formik>
  </div>
);


闰年可以加4天 86 400 000 * 4 = 345 600 000