yup
是一个强大的 JavaScript 对象模式验证库,而 react-hook-form
是一个用于 React 的表单管理库。将两者结合使用可以提供强大的表单验证功能。
yup
提供了丰富的验证规则和自定义验证能力。react-hook-form
提供了高效的表单状态管理和性能优化。适用于需要复杂表单验证的 React 应用,如注册、登录、表单提交等场景。
以下是一个简单的示例,展示如何将 yup
和 react-hook-form
结合使用:
import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
// 定义 yup 验证模式
const schema = yup.object().shape({
name: yup.string().required('Name is required'),
email: yup.string().email('Invalid email').required('Email is required'),
password: yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'),
});
function App() {
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: yupResolver(schema),
});
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>Name</label>
<input {...register('name')} />
{errors.name && <p>{errors.name.message}</p>}
</div>
<div>
<label>Email</label>
<input {...register('email')} />
{errors.email && <p>{errors.email.message}</p>}
</div>
<div>
<label>Password</label>
<input type="password" {...register('password')} />
{errors.password && <p>{errors.password.message}</p>}
</div>
<button type="submit">Submit</button>
</form>
);
}
export default App;
原因:
yupResolver
没有正确导入或使用。解决方法:
yupResolver
并在 useForm
中使用。yup
验证模式是否正确。register
正确注册。解决方法:
可以使用 watch
和 useEffect
结合 yup
进行异步验证。例如:
import React, { useEffect } from 'react';
import { useForm, watch } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
const schema = yup.object().shape({
email: yup.string().email('Invalid email').required('Email is required'),
});
function App() {
const { register, handleSubmit, formState: { errors }, watch } = useForm({
resolver: yupResolver(schema),
});
const email = watch('email');
useEffect(() => {
// 异步验证逻辑
if (email) {
fetch(`/api/validate-email?email=${email}`)
.then(response => response.json())
.then(data => {
if (!data.valid) {
errors.email?.onChange('Email is already taken');
}
});
}
}, [email, errors.email]);
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>Email</label>
<input {...register('email')} />
{errors.email && <p>{errors.email.message}</p>}
</div>
<button type="submit">Submit</button>
</form>
);
}
export default App;
通过这种方式,可以在用户输入时进行实时异步验证。
领取专属 10元无门槛券
手把手带您无忧上云