reactjsyup

Yup validation of website using url() very strict


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


Solution

  • 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