Yup validation of website using url() very strict

SImon Haddad picture SImon Haddad · May 6, 2020 · Viewed 7.4k times · Source

I am trying to validate an input field as a website using

yup.string().url()

But it seems if the protocol is not sent it gives an error, when the website should be flexible to even accept for example stackoverflow.com

pls help

Answer

aturan23 picture aturan23 · May 9, 2020

Instead of using default url validator you can use your own regex. Your code changes like:

website: Yup.string()
        .matches(
            /((https?):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/,
            'Enter correct url!'
        )
        .required('Please enter website'),

You can use your own rule for regex and validate url. You can read more about it there.

Play around with it here: https://regex101.com/r/O47zyn/4