Empty phone number field validation using yup-phone
I recently encountered an issue while using the library yup-phone
yup-phone is a react-library that can be used to validate phone numbers entered in the form field. It uses google-libphonenumber to validate any given phone number in the input field.
Sample usage of yup-phone is given below,
const validationSchema = Yup.object().shape({
mobile: Yup.string().phone()
})
The above schema validates if the given number is a valid phone number format or not. You can read in detail about its usage on the official page.
The problem with the above snippet is it makes the form submission mandatory to provide a phone number even if it is not required. If the field is left empty the validation is made against the empty field. Yup methods optional
and notRequired
didn't work either. (Note: This error is not resolved by yup-phone at the time of writing this post. Please check the official page for tracking the issue.)
Here is a workaround to fix the empty field validation.
const validationSchema = Yup.object().shape({
mobile: Yup.string().when('mobile', {
is: (value) => value?.length > 0,
then: Yup.string().phone(),
otherwise: Yup.string(),
}),
},
[
['mobile', 'mobile']
]
)
Note that the mobile property is written twice in the list of dependencies. This is to avoid cyclic dependency errors as explained in the StackOverflow post.
Below is the code snippet for multiple phone number fields.
const validationSchema = Yup.object().shape({
mobile: Yup.string().when('mobile', {
is: (value) => value?.length > 0,
then: Yup.string().phone(),
otherwise: Yup.string(),
}),
phone: Yup.string().when('phone', {
is: (value) => value?.length > 0,
then: Yup.string().phone(),
otherwise: Yup.string(),
}),
},
[
['mobile', 'mobile'],
['phone', 'phone']
]
)
- Official page for yup-phone: github.com/abhisekp/yup-phone
- Issue: github.com/abhisekp/yup-phone/issues/313