如何用 Yup 验证 material-ui-phone-number

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

我正在尝试使用 YUP 验证 material-ui-phone-number 字段,但是当我将 inputRef prop 提供给组件时,YUP 触发了一个错误 TypeError: e is undefined。 似乎 material-ui-phone-number 组件正在发送值,而 YUP 正在等待一个事件 (e.target.value)

You can check sandbox here

这是我的代码:

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;

您始终可以使用 Controller 组件与任何 third-party 无法使用 out-of-the-box 和 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}
      {...}
    />
  )}
/>

现场演示