react-hook-form use mutiple resolver

Viewed 553

i am trying to create a general input like this

const TextInput = ({
  name,
  register = () => {},
  errors,
  serverErrors,
  ...props
}) => {
  return (
    <div >
      <input
        type="text"
        {...register(name, {
          pattern: { value: /^[A-Za-z]+$/i, message: "Invalid Input" },
        })}
        {...props}
      />
      {errors?.[name] && (
        <span className="text-errorColor">{errors?.[name]?.message}</span>
      )}
    </div>
  );
};

I will use this input in form and use Yup to validate this form


const schema = yup
  .object({
    first_name: yup
      .string()
      .required("This field is required")
      .max(20, "max 20 characters"),
  })
  .required();

const SignupForm = ({ signUpContact, signUpType }) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
            <TextInput
              name="first_name"
              register={register}
              errors={errors}
              serverErrors={error}
              placeholder="First Name"
            />
       </form>
  );
};

but the problem is that the validations in TextInput Competent aren't running i think i can't use Register Validation with Yup validation. as you see I won't duplicate validation [A-Za-z] every time I use TextInput, is there any way to do this?

1 Answers

For input just register the field using react-hook-form

      <input
        type="text"
        {...register(name)}
        {...props}
      />

Use yup to handle all the validation logic

yup
.string()
.trim()
.matches(/^[A-Za-z]+$/i , 'Invalid Input')
.max(20, "max 20 characters"),
.required();
Related