How to show error message using react-hook-form in react

Viewed 5083

How to add validation, I want show error message on for phone number field (helperText, min 10 , max 10 ) and also show error message if submitted without 10 numeric digit

import ReactPhoneInput from "react-phone-input-2"
import {TextField,Button}from "@material-ui/core"

const {register, handleSubmit,formState: { errors }} = useForm()

const getData= (data) => {
   console.log(data.username)
   console.log(data.phone);
}

<form onSubmit={handleSubmit(getData)} >

  <Controller
        control={control}
        name="phone"
        render={({ field: { ref, ...field } }) => (
          <ReactPhoneInput {...field}
            inputExtraProps={{ref, required: true, autoFocus: true }}
            country={"in"}
            onlyCountries={["in"]}
            countryCodeEditable={false}
            specialLabel={"Player Mobile Number"}
          />
        )}
      />
<Button type='submit>Submit</Button> 
</form>
1 Answers

You can use the rules prop of the <Controller /> component to define your validation rules. Check the rules section here for more info.

To display the errors you have to use formState object returned by useForm.

export default function App() {
  const {
    control,
    handleSubmit,
    formState: { errors }
  } = useForm();

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

  const isNumber = (number) => !isNaN(number) || "Must be a number";

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        control={control}
        name="phone"
        rules={{
          required: { value: true, message: "Required" },
          minLength: { value: 12, message: "Min Length" },
          maxLength: { value: 12, message: "Max Length" },
          validate: isNumber
        }}
        render={({ field: { ref, ...field } }) => (
          <ReactPhoneInput
            {...field}
            inputExtraProps={{
              ref,
              required: true,
              autoFocus: true
            }}
            country={"in"}
            onlyCountries={["in"]}
            countryCodeEditable={false}
            specialLabel={"Player Mobile Number"}
          />
        )}
      />
      {errors.phone && <p>{errors.phone.message}</p>}
      <input type="submit" />
    </form>
  );
}

Edit React Hook Form - react-phone-input-2 (forked)

Related