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

Viewed 6004
  • We have a 3rd party component that we want to use SecondaryInput
  • Want to use Yup validation (don't know how to use yup with the rule props, in Controller component)
  • Controlled component is inside the child component so I am using the useFormContext
  • Schema code is not working

My code is something like this

NOTE: I can not use the ref inside the custom component as it does not take props like ref

Parent component

  const schema = yup.object().shape({
    patientIdentity: yup.object().shape({
      firstName: yup.string().required('Required field'),
      lastName: yup.string().required('Required field'),
    }),
  });
  const methods = useForm();
  const {
    errors,
    handleSubmit,
    register,
    setValue,
    reset,
    getValues,
  } = useForm({
    defaultValues: {
      patientIdentity: {
        firstName: 'test 1',
        lastName: 'Test 2',
      },
    },
    validationSchema: schema,
  });

  const onSubmit = (data, e) => {
    console.log('onSubmit');
    console.log(data, e);
  };

  const onError = (errors, e) => {
    console.log('onError');
    console.log(errors, e);
  };
  console.log('errors', errors); // Not able to see any any error 
  console.log('getValues:> ', getValues()); Not able to see any any values
  return (
    <View style={[t.flex1]}>
      {/* Removed code from here */}
      <View style={[t.flex1, t.selfCenter]}>
       
        <FormProvider {...methods}>
          <View style={[t.flexCol]}>
            <PatientForm /> // <<Child component
            <PrimaryButton
              style={[t.pL3, t.h10]}
              onPress={handleSubmit(onSubmit, onError)}
            >
              Save changes
            </PrimaryButton>
          </View>
        </FormProvider>
      </Row>
    </View>

Child component

  const {
    control,
    register,
    getValues,
    setValue,
    errors,
    defaultValuesRef,
  } = useFormContext();

  console.log('errors:>>', errors); // NOt able to log
  console.log('Identity | getValues>', getValues());
  return (
    <DetailCard title="Identity">
      <Controller
        control={control}
        render={(props) => {
          const { onChange, onBlur, value } = props;
          return (
            <SecondaryInput
              label="Legal First Name"
              value={value}
              onTextChange={(value) => onChange(value)}
              onBlur={onBlur}
            />
          );
        }}
        name="patientIdentity.firstName"
        rule={register({
          required: ' name cannot be empty',
          })}
        defaultValue=""
      />
      <Controller
        control={control}
        as={({ onChange, onBlur, value }) => {
          return (
            <SecondaryInput
              label="Legal Last Name"
              value={value}
              onTextChange={(value) => onChange(value)}
              onBlur={onBlur}
            />
          );
        }}
        name="patientIdentity.lastName"
        rules={{
          required: 'this is required field',
          message: 'required field',
        }}
        defaultValue=""
      />
</DetailCard>
)
1 Answers

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.
Related