首页 > 解决方案 > 是的,使用动态数据进行验证

问题描述

我对反应钩子表单的 API 响应要求进行了 yup 验证。我的表格是这样的:

import React from "react";
import useForm from "react-hook-form";
import { schema } from "./schema";
import { useTestProps } from "./useTestProps";

function Sub({ title, showForm }) {
  const { register, handleSubmit, errors } = useForm({
    validationSchema: schema
  });

  const { data } = useTestProps();


  const onSubmit = (data) => {
   //submit form
  };
  // console.log(errors);
  return (
    <div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <label>{title}</label>
        <input type="text" name="iip" ref={register} />
        <br />
        {errors.iip && <p>{errors.iip.message}</p>}
        <br />
        <label>Email</label>
        <input type="text" name="email" ref={register} />
        <br />
        {errors.email && <p>{errors.email.message}</p>}
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

export default Sub;

表单的验证模式是这样的,

//schema.js

import * as yup from "yup";

export const schema = yup.object().shape({
  iip: yup
    .string()
    .required()
    .test("validate with testProps", "iip not found", (value) => {
      // validate that value should be one of testProps
      // if value is in data, return true, or return false
      return true
    }),
  email: yup.string().email().required()
});

我的要求是使用从useTestProps中的 API 调用返回的数据验证iip字段, 如下所示,

{
  "data": ["test1", "test2", "test3"]
}

如何访问模式对象测试中的数据,我可以将用户输入的值与 JSON 响应进行比较?

标签: validationyupreact-hook-form

解决方案


推荐阅读