问题描述
我在一个用Yup验证的Formik表单中使用了Reaction-Datepicker。为了将Reaction-Datepicker集成到Formik中,我使用了wrapper solution in this thread。
最初输入值时,将检查.required()
,但不会检查其他任何验证。因此,我不会立即获得StartDate later than today
验证。如果我再次进入该控件并退出,则会触发这些其他验证。因此,唯一会立即发生的初始验证错误是.required()
,但对于任何其他错误,我需要重新触摸该控件。有什么解决方案吗?
编辑:我注意到Formik的.touched
没有在第一个日期选择器输入上设置。仅在后续触摸/输入时设置。
是的
startDate: yup.date().nullable().required('Start Date is required')
.min(new Date(), 'Start Date must be later than today'),
日期选择器包装-see this thread-记入ToolmakerStever
我尝试添加onCalendarClose
以强制按此日期选择器issue report重新验证,这确实可能正在发生,但这也可能是YUP架构问题--我不确定。
const { setFieldValue, validateField, values, handleBlur } = useFormikContext();
return (
<DatePicker
{...field}
{...props}
showMonthDropdown
showYearDropdown
selected={(field.value && new Date(field.value)) || null}
onChange={val => {
setFieldValue(field.name, val);
}}
onCalendarClose={val => {
// Force-validate onCalendarClose to avoid any potential DatePicker Blur issues
// Didn't help
validateField(props.name);
}}
onBlur={e => {
// Call Formik's handleBlur
// Didn't help
handleBlur(e);
}}
/>
)
推荐答案
我找到了修复程序。第一次没有将DatePicker标记为touched
。DatePicker公开了一个名为onChangeRaw
的事件,我在该事件中强制触摸了控件。现在,所有错误都立即触发,无需重新触摸。
onChangeRaw={e => {
setFieldTouched(field.name, true, true);
}}
这放在Formik的日期选择器包装中,as shown in this post。
Reaction-DatePicker由于某种原因与Blur有错误,documented here。他们的模糊建议包括调用onCalendarClose
或onChangeRaw
。但只有onChangeRaw
对我来说是可靠的。