Gustavo Monteiro
Gustavo Monteiro

Reputation: 33

How to validate material-ui-phone-number with Yup

I am trying to validate a material-ui-phone-number field with YUP but when I had the inputRef prop to the component YUP triggers an error saying TypeError: e is undefined. It seems that the material-ui-phone-number component is sending the value and YUP is expecting an event (e.target.value)

You can check sandbox here

This is my code:

import React, { useState } from "react";
import MuiPhoneNumber from "material-ui-phone-number";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers";
import * as yup from "yup";

const Step1Schema = yup.object().shape({
  name: yup.string().required("O campo nome é obrigatório"),
  email: yup
    .string()
    .required("O campo email é obrigatório")
    .email("Formato de email inválido"),
  phone: yup.mixed().test((value) => console.log(value))
});

const Step1 = ({ formData, nextStep, formStepData }) => {
  const { register, handleSubmit, errors } = useForm({
    resolver: yupResolver(Step1Schema)
  });

  const onSubmit = async (data) => {
    console.log(data);
  };

  const [phone, setPhone] = useState("");
  return (
    <div data-aos="fade-up" id="house-form">
      <form onSubmit={handleSubmit(onSubmit)}>
        <MuiPhoneNumber
          id="contactPhoneNumber"
          inputRef={register}
          defaultCountry={"pt"}
          style={{ width: "100%" }}
          name="phone"
          label="Contacto telefónico"
          variant="outlined"
          margin="normal"
          value={phone}
          onChange={(value) => setPhone(value)}
          error={Boolean(errors.phone)}
        />
      </form>
    </div>
  );
};

export default Step1;

Upvotes: 1

Views: 3692

Answers (1)

NearHuscarl
NearHuscarl

Reputation: 81340

You can always use Controller component to integrate with any third-party input components that do not work out-of-the-box with react-hook-form.

const { control, ... } = useForm();

...

<Controller
  name="phone"
  control={control}
  render={({ name, onBlur, onChange, value }) => (
    <MuiPhoneNumber
      name={name}
      value={value}
      onBlur={onBlur}
      // onChange pass the raw value so you can access it using e instead of
      // e.target.value. props.onChange can accept the value directly
      onChange={onChange}
      {...}
    />
  )}
/>

Live Demo

Edit 64024619/how-to-validate-material-ui-phone-number-with-yup/

Upvotes: 2

Related Questions