我正在尝试使用yup构建类似于Formik的东西,除验证表单的功能外,所有功能均有效。
我正在使用最新版本的svelte(不是alpha版本)。
const createFormik = () => {
const { subscribe, set, update } = writable({
values: {},
validationSchema: {},
errors: {}
});
const validate = () => {
let newErrors = {};
update(object => {
object.validationSchema.validate(object.values, { abortEarly: false })
.catch(errors => {
errors.inner.forEach(error => {
newErrors = {...newErrors, [error.path]: error.errors }
});
});
return {...object, errors: newErrors};
})
}
return {
subscribe,
update,
setInitialValues: (initialValues) => update(n => ({ ...n, values: initialValues })),
setValidationSchema: (validationSchema) => update(n => ({ ...n, validationSchema: validationSchema })),
setErrors: (errors) => update(n => ({ ...n, errors: errors })),
validateSchema: () => validate(),
updateFieldValue: (name, value) => update(n => ({ ...n, values: { ...n.values, [name]: value } }))
}
}
更新程序不使用匹配的错误更新存储中的错误对象,而是返回空错误对象。
答案 0 :(得分:0)
就像里奇·哈里斯(Rich Harris)所说的那样,问题是,我在更新函数中使用了promise。 在诺言之后或在诺言内部解决更新。
const createFormik = () => {
const { subscribe, set, update } = writable({
values: {},
validationSchema: {},
errors: {}
});
const validate = (object) => {
let newErrors = {};
object.validationSchema.validate(object.values, { abortEarly: false })
.catch(errors => {
errors.inner.forEach(error => {
newErrors = { ...newErrors, [error.path]: error.errors }
});
console.log(object);
update(n => ({ ...n, errors: newErrors }));
});
update(n => ({...n, errors: {}}));
}
return {
subscribe,
update,
setInitialValues: (initialValues) => update(n => ({ ...n, values: initialValues })),
setValidationSchema: (validationSchema) => update(n => ({ ...n, validationSchema: validationSchema })),
setErrors: (errors) => update(n => ({ ...n, errors: errors })),
validateSchema: (object) => validate(object),
updateFieldValue: (name, value) => update(n => ({ ...n, values: { ...n.values, [name]: value } }))
}
}