我正在尝试使用 react-hook-form 的 useFieldArray
创建动态表单钩。用户应该能够添加或删除字段,从而使其动态化。我看过这个tutorial寻求灵感,但缺少的部分是如何对状态进行错误验证,这将是一个对象数组:{email: string}[]
. (该对象将采用更多键/值对。为简单起见,我省略了其余部分。)
我试过使用 yup
作为验证模式。它看起来像这样:
const schema = yup.array().of(
yup.object().shape({
email: yup.string().email().required(),
}),
)
react-hook-form 的实现是:import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { useForm, useFieldArray, Controller } from 'react-hook-form'
const { register, control, handleSubmit, errors } = useForm({
resolver: yupResolver(schema),
mode: 'onChange',
})
const { fields, append, remove } = useFieldArray({
control,
name: 'users',
})
根据上面链接中的教程,表格或多或少。当控制台记录
error
来自 useForm
的对象钩子(Hook)它始终给出一个空对象{}
.它似乎不起作用。我可能在这里遗漏了一些东西。问题是什么?
最佳答案
也许您想使用 context
切换架构的参数?
Context: This context object is mutable and will be injected into resolver's second argument or Yup validation's context object.
import * as React from "react";
import { useForm } from "react-hook-form";
import * as Joi from "joi";
const validationSchema1 = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required()
});
const validationSchema2 = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required()
});
const App = () => {
const [schemaContext, setSchemaContext] = useState({ schemaA: false })
const { register, handleSubmit, errors } = useForm({
context: schemaContext, // use the context switch here
resolver: async (data, context) => {
const { error, value: values } = context.is1 ? validationSchema1.validate(data, {
abortEarly: false
}) : validationSchema2.validate(data, {
abortEarly: false
});
return {
values: error ? {} : values,
errors: error
? error.details.reduce((previous, currentError) => {
return {
...previous,
[currentError.path[0]]: currentError
};
}, {})
: {}
};
}
});
const onSubmit = data => {
console.log(data)
};
return (
<div className="App">
<h1>resolver</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<label>Username</label>
<input type="text" name="username" ref={register} />
{errors.username && <p>errors.username.message</p>}
<input type="submit" />
</form>
</div>
);
};
关于javascript - 如何使用带有 useFieldArray 的 react-hook-form 对动态表单进行 yup 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66266929/