首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何将yup validationSchema与react-hook-form一起使用?

基础概念

yup 是一个强大的 JavaScript 对象模式验证库,而 react-hook-form 是一个用于 React 的表单管理库。将两者结合使用可以提供强大的表单验证功能。

相关优势

  1. 强大的验证能力yup 提供了丰富的验证规则和自定义验证能力。
  2. 高效的表单管理react-hook-form 提供了高效的表单状态管理和性能优化。
  3. 良好的集成:两者可以无缝集成,提供一致的用户体验。

类型

  • 同步验证:在提交表单时进行验证。
  • 异步验证:在用户输入时进行实时验证。

应用场景

适用于需要复杂表单验证的 React 应用,如注册、登录、表单提交等场景。

示例代码

以下是一个简单的示例,展示如何将 yupreact-hook-form 结合使用:

代码语言:txt
复制
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;

参考链接

常见问题及解决方法

问题:为什么验证不生效?

原因

  1. yupResolver 没有正确导入或使用。
  2. 验证模式定义错误。
  3. 表单字段没有正确注册。

解决方法

  1. 确保正确导入 yupResolver 并在 useForm 中使用。
  2. 检查 yup 验证模式是否正确。
  3. 确保表单字段通过 register 正确注册。

问题:如何处理异步验证?

解决方法: 可以使用 watchuseEffect 结合 yup 进行异步验证。例如:

代码语言:txt
复制
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;

通过这种方式,可以在用户输入时进行实时异步验证。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券