Is it possible to define multiple regular expressions for a single field using yup in a form validation?

My goal is to validate an input to only accept URLs in Google Maps format. There are three possible valid outputs for a Google Maps URL:

  1. (for Google Maps app)
  2. (I only want to focus on )
  3. (when sharing directly from Google Maps)

Currently, I am able to handle the first scenario and I believe I can use regular expressions to validate the URLs. However, my question is how to enable multiple regular expression validations using the Yup validator with React Hook Forms. Here's what I have so far:

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

I have attempted to use different matches, but it does not work because it tries to validate both match conditions as true:

For example, with an input like


const areaSchema = yup.object().shape({
...
    urlGoogleMaps: yup.string()
        .matches(/^https\:\/\/goo\.gl\/maps\//, 'Invalid Google Maps URL') * Validates
        .matches(/^https\:\/\/goo\.gl\/secondMaps\//, 'Invalid Google Maps URL') * Does not validate, making it invalid
        .required(requiredMessage),
...
});

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

Answer №1

Is it possible that the test function will function correctly?

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

Customize the datepicker locale in Valor

Currently, I am working with Angular2 and typescript alongside the Valor datepicker. Unfortunately, the datepicker does not have the necessary locale built-in. After some research, I discovered that the essential JavaScript file containing the locale infor ...

Using JavaScript to convert date and time into ISO format

Similar Question: How do I output an ISO-8601 formatted string in Javascript? I've been attempting to change a date and time input into an ISO format but keep encountering the error .toISOString is undefined. It seems like I must be overlooking s ...

Issue: Unable to locate a matching object '[object Object]' of type 'object'. NgFor can solely bind to data structures like Arrays and Iterables

I am facing an error that says "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." I am trying to create a Notification list but I can't figure out w ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

Local variable reference getting lost in a loop during a jQuery Ajax call

Currently, I am facing an issue with my jQuery ajax calls within a loop. The problem arises when each ajax call returns and I need to retrieve a specific value associated with the original call. However, due to further iterations in the loop, the value of ...

What is the best way to remove linear-gradient effects applied by a dark mode theme?

Why does MUI add random gradients to components, like in dark mode? Is there a way to disable this feature because it doesn't match the exact color I expected for my custom theme... My Theme Options export const themeOptions: ThemeOptions = { palette ...

What is the best time to fetch the height of an element containing an image?

I am working on my web app and I want to implement a popup element that contains an <img> element. Typically, the image source is larger than necessary, so I resize it using CSS. However, before displaying the popup, I need to determine its outerHeig ...

What are the best techniques for streamlining nested objects with Zod.js?

As a newcomer to zod.js, I have found that the DataSchema function is extremely helpful in verifying API data types and simplifying the API response easily. However, I'm curious if there is a way to streamline the data transformation process for myEx ...

Encountering difficulties in accessing files displayed by serve-index in Express

My Node.js server using Express seems to be working fine for displaying directory contents, but I'm running into an issue when trying to access individual files. After clicking on a file listed in the directory, I keep getting an error message that sa ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

The withRouter function in React Router does not automatically inject the router

Desiring to implement withRouter on my primary React component named 'App'. You can view the documentation here. This is how I utilize it: import React from "react"; import { render } from "react-dom"; import {Router, Link, hashHistory, Rout ...

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...

Issue with dat.gui not displaying correctly within a WebGL container

When attempting to display my dat.gui interface with a button and textbox on top of my WebGL window, I encounter this issue: https://i.sstatic.net/N9peP.png The section for "Close Controls" in the dat.gui is visible, but strangely the button and textbox ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Data is not appearing as expected in the React component when using the data

I'm currently facing an issue while working with MUI. I am able to retrieve the list in console.log, but nothing is being displayed on the screen - no errors or data, just the console.log output. Here is a snippet of the data that I am receiving: ...