DEV Community

Sainath Ramanathan
Sainath Ramanathan

Posted on • Originally published at sainath.tech on

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()
})

Enter fullscreen mode Exit fullscreen mode

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']
    ]
)

Enter fullscreen mode Exit fullscreen mode

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']
    ]
)

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
liyang51827 profile image
Yang Li

I had a same problem with yup-phone module.
Instead, I used this NPM module to fix my issue.
github.com/csandman/yup-phone-lite