phone-number-input](https://gitlab.com/catamphetamine/react-phone-number-input#readme) with react-hook-form and it works normally. I want to validate the phone number with isValidPhoneNumber from react-phone-number-input but I do not know how to achieve that with react-hook-form. I have read some posts here about this problem but there's no correct answer for me. Here is my code:
import { useForm, Controller } from 'react-hook-form'
import PhoneInput, { isValidPhoneNumber } from 'react-phone-number-input'
import 'react-phone-number-input/style.css'
const MyForm = () => {
const {
handleSubmit,
formState: { errors },
control,
} = useForm()
const onSubmit = (data) => {
console.log(data)
}
return (
<form onSubmit={handleSubmit(onSubmit)} className="user-info-form">
<div>
<label htmlFor="phone-input">Phone Number</label>
<Controller
name="phone-input"
control={control}
rules={{ required: true }}
render={({ field: { onChange, value } }) => (
<PhoneInput
value={value}
onChange={onChange}
defaultCountry="TH"
id="phone-input"
/>
)}
/>
{errors.phone && <p className="error-message">Invalid Phone</p>}
</div>
</form>
)
}
export default MyForm
You can achieve this by passing isValidPhoneNumber method for the validate key of the rules prop of the controller.
And you have done a typo as well. In your the Controller name is phone-input. So, you have to check for the phone-input key in the errors object instead of phone.
Please find the answer.
import React from "react";
import { useForm, Controller } from "react-hook-form";
import PhoneInput, { isValidPhoneNumber } from "react-phone-number-input";
import "react-phone-number-input/style.css";
const MyForm = () => {
const {
handleSubmit,
formState: { errors },
control
} = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="user-info-form">
<div>
<label htmlFor="phone-input">Phone Number</label>
<Controller
name="phone-input"
control={control}
rules={{
validate: (value) => isValidPhoneNumber(value)
}}
render={({ field: { onChange, value } }) => (
<PhoneInput
value={value}
onChange={onChange}
defaultCountry="TH"
id="phone-input"
/>
)}
/>
{errors["phone-input"] && (
<p className="error-message">Invalid Phone</p>
)}
</div>
</form>
);
};
export default MyForm;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With