我具有以下Formik表单,其中包含一个下拉列表和两个日期选择器。日期选择器具有条件验证:对于这两个日期选择器,如果用户都从下拉列表中选择了“第一项”,则我们将创建字段required
。
但是,对于第二个DatePicker(EndDate)-我希望进行额外的验证,以将日期限制为距StartDate不超过6个月,且不得小于StartDate。并且只有在用户将First
作为选定项的情况下,才应应用 。
<Formik
initialValues={{ Dropdown1: "", StartDate: "", EndDate: "" }}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
validationSchema={Yup.object().shape({
StartDate: Yup.date.when("Dropdown1", (data, schema) => {
data.Dropdown1 === "First" ? schema.required("this is a required field") : schema
})
EndDate: Yup.date.when("Dropdown1", (data, schema) => {
data.Dropdown1 === "First" ? schema.required("this is a required field") : schema
// Here I need another validation that checks EndDate can't be more than 6 months from StartDate and never less than StartDate
})
})}
render={props => (
<form onSubmit={props.handleSubmit}>
<CustomDropdown
dropdownItems=[
{ caption: "Select something", Id: "" },
{ caption: "First", Id: "1" },
{ caption: "Second", Id: "2" }
]
onBlur={props.handleBlur}
value={props.values.name}
name="Dropdown1"
/>
<CustomDatePicker
name="StartDate"
/>
<CustomDatePicker
name="EndDate"
/>
{props.errors.name && <div id="feedback">{props.errors.name}</div>}
<button type="submit">Submit</button>
</form>
)}
/>
我该如何实现?