3 回答
TA贡献1862条经验 获得超7个赞
您需要交换日期参数:
differenceInYears(new Date(), new Date(value)) >= 18;
如果您检查 date-fns,第一个参数应该是较晚的日期。
您还需要将字段值解析为Date
.
TA贡献1796条经验 获得超7个赞
因此,如果您想在不添加 date-fns 插件的情况下执行此操作并且不想使用 mgic 天数,那么您可以执行类似的操作。
dob: Yup.date().nullable()
.test('dob', 'Should be greater than 18', function (value, ctx) {
const dob = new Date(value);
const validDate = new Date();
const valid = validDate.getFullYear() - dob.getFullYear() >= 18;
return !valid ? ctx.createError() : valid;
})
.required('Required'),
TA贡献1864条经验 获得超6个赞
我的解决方案:
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
添加回答
举报