使用带有react-hook-form的yup验证模式跳过fieldArray表单中最后一个对象的验证,可以通过以下步骤实现:
import { useForm, useFieldArray } from 'react-hook-form';
import * as yup from 'yup';
users
的fieldArray,其中包含name
和email
字段。const schema = yup.object().shape({
users: yup.array().of(
yup.object().shape({
name: yup.string().required('Name is required'),
email: yup.string().email('Invalid email').required('Email is required'),
})
),
});
useForm
和useFieldArray
钩子,以及yup验证模式的schema。const MyComponent = () => {
const { control, handleSubmit, register, errors } = useForm({
resolver: yupResolver(schema),
});
const { fields, append, remove } = useFieldArray({
control,
name: 'users',
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((field, index) => (
<div key={field.id}>
<input
name={`users[${index}].name`}
defaultValue={field.name}
ref={register}
/>
<input
name={`users[${index}].email`}
defaultValue={field.email}
ref={register}
/>
{errors.users && errors.users[index] && (
<p>{errors.users[index].name?.message}</p>
)}
<button type="button" onClick={() => remove(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={() => append({ name: '', email: '' })}>
Add User
</button>
<button type="submit">Submit</button>
</form>
);
};
fields.map
来遍历fields
数组,并为每个字段渲染相应的输入框。同时,我们还检查了errors.users
和errors.users[index]
,以显示验证错误信息。fields
数组中移除最后一个对象。const onSubmit = (data) => {
const lastFieldIndex = fields.length - 1;
fields.splice(lastFieldIndex, 1);
console.log(data);
};
通过以上步骤,我们可以使用带有react-hook-form的yup验证模式跳过fieldArray表单中最后一个对象的验证。请注意,这里的示例仅用于演示目的,实际应用中可能需要根据具体需求进行适当修改。
领取专属 10元无门槛券
手把手带您无忧上云