使用Formik和YUP的Reaction-Date Picker:未在第一個模糊時驗證日期值,而不是.Required() [英] React-Datepicker with Formik and Yup: Date value not validated on first blur, other than .required()
問題描述
我在一個用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
的事件,我在該事件中強制觸摸了控件?,F在,所有錯誤都立即觸發,無需重新觸摸。
onChangeRaw={e => {
setFieldTouched(field.name, true, true);
}}
這放在Formik的日期選擇器包裝中,as shown in this post。
Reaction-DatePicker由于某種原因與Blur有錯誤,documented here。他們的模糊建議包括調用onCalendarClose
或onChangeRaw
。但只有onChangeRaw
對我來說是可靠的。
這篇關于使用Formik和YUP的Reaction-Date Picker:未在第一個模糊時驗證日期值,而不是.Required()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!