Validate Phone Number With Yup

Yup phone number validation doesn't works

You are validating it as a number and not as a string, thus .min in this case means that number value has to be minimum 7. It's not a length. You have to validate it as a string and use a regexp pattern. Example:

phoneSchema = Yup.string().matches(new RegExp('[0-9]{7}'))

And then you can also make it more advanced.

Regular expression to validate US phone numbers using Formik and Yup

Try this regex it can meet your requirements

 /^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$/

It would look something like that:

validationSchema={Yup.object({
AdministratorCell: Yup.string()
.matches(/^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$/, {
message: "Invalid phone number",
excludeEmptyString: false,
})
})}

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

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/



Related Topics



Leave a reply



Submit