How to use Yup validation schema with the Controller component in `react-hook-form` lib

There are a couple of things you need to check:

  • The schema object does not depend on any local-scoped variables. You can put it outside of the function so the component doesn’t recreate it every time it renders

  • Pass the yup schema object to a yupResolver first instead of passing directly to the resolver

import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from "yup";

const schema = yup.object().shape({
  patientIdentity: yup.object().shape({
    firstName: yup.string().required('Required field'),
    lastName: yup.string().required('Required field'),
  }),
});

const App = () => {
  const { ... } = useForm({
    resolver: yupResolver(schema),
  });

  return (...);
};
  • If you write validation rules using third-party library like Yup, you can remove the rules props from the Controller since they’re duplicated.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top