使用 yup 和 formik 验证 2 个字段
Validation 2 fields with yup and formik
这是我的默认值:
const defaultValues = {
busi_day: [],
busi_start_time: '09:00',
busi_end_time: '17:00',
};
这是我的 2 个字段:
<FastField type="time" className="start-time" name="busi_start_time" value={values.busi_start_time} />
<FastField type="time" className="start-time" name="busi_end_time" value={values.busi_end_time} />
这是我使用 Yup 进行的验证:
const validationSchema = Yup.object().shape({
busi_start_time: Yup.string()
.required(),
busi_end_time: Yup.string()
.required(),
});
现在,我想验证 busi_end_time 必须在 busi_start_time 之后。例如:
{busi_start_time: '09:00' busi_end_time: '17:00'} 有效但 {busi_start_time: '14:00' busi_end_time: '08:00' } 无效。我该怎么做?
使用 moment.js 库和下面的代码:
Yup.object().shape({
busi_start_time: Yup.string().required("Start time cannot be empty"),
busi_end_time: Yup.string()
.required("end time cannot be empty")
.test("is-greater", "End time should be greater", function (value) {
const { busi_start_time} = this.parent;
return moment(value, "HH:mm").isSameOrAfter(moment(busi_start_time, "HH:mm"));
})
});
这是我的默认值:
const defaultValues = {
busi_day: [],
busi_start_time: '09:00',
busi_end_time: '17:00',
};
这是我的 2 个字段:
<FastField type="time" className="start-time" name="busi_start_time" value={values.busi_start_time} />
<FastField type="time" className="start-time" name="busi_end_time" value={values.busi_end_time} />
这是我使用 Yup 进行的验证:
const validationSchema = Yup.object().shape({
busi_start_time: Yup.string()
.required(),
busi_end_time: Yup.string()
.required(),
});
现在,我想验证 busi_end_time 必须在 busi_start_time 之后。例如: {busi_start_time: '09:00' busi_end_time: '17:00'} 有效但 {busi_start_time: '14:00' busi_end_time: '08:00' } 无效。我该怎么做?
使用 moment.js 库和下面的代码:
Yup.object().shape({
busi_start_time: Yup.string().required("Start time cannot be empty"),
busi_end_time: Yup.string()
.required("end time cannot be empty")
.test("is-greater", "End time should be greater", function (value) {
const { busi_start_time} = this.parent;
return moment(value, "HH:mm").isSameOrAfter(moment(busi_start_time, "HH:mm"));
})
});