javascripttypescriptnext.jsreact-hook-formyup

How can I specify different regexp for a single field using yup?


I have an input that I want to validate to only accept Google Maps type of URL. AFAIK, I have three posible outputs for google maps that I want to accept as valid, being these:

  1. https://maps.app.goo.gl/SomeString (for google maps app)
  2. https://www.google.com.mx/maps/SomeReallyBigStringAndOtherParams (I only want to care for https://www.google.com.mx/maps/)
  3. https://goo.gl/maps/SomeString (when sharing directly from maps)

Right now I can handle the first scenario, and I thing I can make my way out of the regular expressions, but my question is how to enable multiple regexp validations using Yup validator and React hook forms. I have the following:

const areaSchema = yup.object().shape({
...
    urlGoogleMaps: yup.string()
        .matches(/^https\:\/\/goo\.gl\/maps\//, 'Invalid google maps URL')
        .required(requiredMessage),
...
});

I've tried using different matches, but it doesn't work because it tries to validate both of matches conditions as true:

Having an input as https://goo.gl/maps/


const areaSchema = yup.object().shape({
...
    urlGoogleMaps: yup.string()
        .matches(/^https\:\/\/goo\.gl\/maps\//, 'Invalid google maps URL') * Checks
        .matches(/^https\:\/\/goo\.gl\/secondMaps\//, 'Invalid google maps URL') * Doesn't check, so its invalid
        .required(requiredMessage),
...
});

Is there a way to validate multiple strings using multiple .matches()?


Solution

  • Would test work?

    const urlValidationSchema = Yup.string().test(
      'is-valid-url',
      'invalid-url',
      (value) => 
        /^(http|https):\/\/google\.com$/.test(value) ||
        /^(http|https):\/\/secondmaps\.com$/.test(value) ||
        /^(http|https):\/\/somethingelse\.com$/.test(value)
    )
    .required(requiredMessage);