yup validation with dynamic data

Viewed 741

I have a yup validation with API response requirement for a react hook form. My form is like:

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;

Validation schema of the form is like this,

//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()
});

My requirement is to validate iip field with data returned from API call in useTestProps which is like this,

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

How can I access data in schema object test where I can compare user entered value with JSON response?

0 Answers
Related