Is there a way to compare two regex values using vuelidate?

Can someone assist me with validating an input field using vuelidate? I am looking to return a valid result if either of the two regular expressions provided below is true.

const val1 = helpers.regex('val1', /^\D*7(\D*\d){12}\D*$/)
const val2 = helpers.regex('val2', /^\D*1(\D*\d){11}\D*$/)

const checkvals = () => {
  if(val1 || val2) {
      return true
  } else{
      return false
  }
}

Validation

numbercheck: {
      required,
      checkvals
    },

Any suggestions on how I can make this work?

Possible Solution

import { or, helpers, required } from 'vuelidate/lib/validators'

    const val1 = helpers.regex('val1', /^\D*7(\D*\d){12}\D*$/)
    const val2 = helpers.regex('val2', /^\D*1(\D*\d){11}\D*$/)


    checkvals: {
      numbercheck,
      valid: or(val1, val2) 
    },

Alternative Solution

const numbercheck = helpers.regex("mob", /^\D*(?:7(?:\D*\d){12}|1(?:\D*\d){11})\D*$/);

Validation

checkvals: {
      required,
      numeric,
      numbercheck,
    },

Answer №1

Consider using a single pattern instead of a conditional operator by combining 7(\D*\d){12} and 1(\D*\d){11} into an alternation since the start and end of the pattern are identical.

If you do not require the capturing group's value later on, you can convert it to a non-capturing group using (?:

In the second part, I believe that 11} should actually be a quantifier like {11}

The revised pattern appears as follows:

^\D*(?:7(?:\D*\d){12}|1(?:\D*\d){11})\D*$

Explanation

  • ^\D* Beginning of the string and match 0+ non-digits
  • (?: Non-capturing group for the alternative
    • 7(?:\D*\d){12} Match the digit 7 followed by 12 digits separated by optional non-digits
    • | Or
    • 1(?:\D*\d){11} Match the digit 1 followed by 11 digits separated by optional non-digits
  • ) Close the non-capturing group
  • \D*$ Match optional non-digits and confirm the end of the string

Check out this regex demo

Answer №2

Even though this answer may seem outdated, the latest version of @vuelidate/validators: 2.0.4 no longer requires importing from 'vuelidate/lib/validators'. This change causes

An error when trying to import "vuelidate/lib/validators"

You can now import it like this

import { helpers } from "@vuelidate/validators";

I hope this information proves helpful to someone.

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

What is the process for creating unit tests for a method that utilizes the @Transaction() decorator?

I am currently using NestJS 6 and TypeORM to interact with a MySQL database. While attempting to write unit tests for a method that utilizes the @Transaction() and @TransactionManager() decorators, I encountered the following error message: ConnectionNotF ...

css background is repeating after the height of the div is reset

I'm working on a project where I want to resize an image while maintaining its aspect ratio to fit the height/width of the browser window. However, every time the code for resizing is implemented, the div height continues to increase with each resize ...

Populate a secondary dropdown menu using the selection from a primary dropdown menu and retrieve the corresponding "value" instead of displaying the value as a dropdown option

I am attempting to create two dropdowns that are populated by another dropdown. Below is the code: HTML: <form type=get action="action.php"> <select name="meal" id="meal" onChange="changecat(this.value);"> <option value="" disabled select ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

What is preventing my content from showing up when clicked like this?

I have created a javascript script to reveal hidden content, but for some reason it is not working when I click on it. Can anyone provide assistance? Below is the script I am using: <script src="style/jquery/jquery.js"></script> <script> ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Ways to troubleshoot issues that arise when updating the node version

After upgrading my version, I encountered a serious error. I developed a program a few years ago using version 18.x. Now that I have upgraded node.js, I am facing some errors. Below are the error messages: ERROR in ./app/assets/scss/styles.scss (./node_mo ...

Preventing v-list-item-group from being deselected in Vuetify

Currently, my setup includes a v-list and v-list-item-group, resembling the example provided in the Vuetify documentation: https://vuetifyjs.com/en/components/lists/#flat The issue arises when a user clicks on the same v-list-item twice, causing it to be ...

Utilizing ReactJS to make an Ajax request

I am trying to transfer data to individuals and then display it using the array map function. export default class App extends Component { constructor(props) { super(props); this.state = { persons: [], }; } componentDidMount() { $ ...

Issue: Elements within an iteration must include a 'v-bind:key' directive. Vue/Require-v-for-key error detected

As someone who is just starting to learn Vue, I recently attempted to create a commercial product page by following a tutorial. However, upon trying to run 'npm run serve', I encountered an error that read: Error: Elements in iteration expect to ...

The HTML drag and drop API is causing an issue where the `getData`

My website features a drag-and-drop functionality, and I'm utilizing the HTML drag-and-drop API to implement it. However, when I attempt to drag and drop an SVG image onto the canvas, it displays as undefined, and I would like the image to remain in t ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...

What order do Node.js event queues, Promises, and setTimeout() operate in?

QUERY: When working with Node.js event queues, such as code like "new Promise((r) => setTimeout(r, t));", where exactly is the setTimeout() function evaluated? Is it immediate, in the microqueue for Promise resolutions, or elsewhere? INSIGHT ...

Box Pattern with Pop-Up Modal

Check out the grid of squares I've coded below: <div class='square-container'> <div class='square'></div> <div class='square'></div> <div class='square'></div& ...

Having trouble creating a scatter chart using vue-charts library

Whenever I try to render the chart, all I get is a blank page along with this error message: TypeError: Cannot read property 'getBasePixel' of undefined There seems to be an issue with my implementation in Vue.js even though I followed the ex ...

Issue with updating Angular list reference when deleting an item

My current task involves implementing a feature that displays selected items from a hierarchical structure on the right side. slice.component.ts : import { Component, Input, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core&a ...

Various input tools available for every Textarea

I'm grappling with this particular case. Each textarea should have its own toolbox, but currently only one is active (I anticipate having more than 2 areas, so JavaScript needs to be able to recognize them by ID) I attempted to use something like: f ...

Divide information in the chart

<table id="tab"> <tr><td class="sub">mmmmm</td><td class="sub">jjjjj</td></tr> <tr><td class="sub">lllll</td><td class="sub">wwwww&l ...

The selected attribute does not function properly with the <option> tag in Angular

Currently, I am faced with a challenge involving dropdowns and select2. My task is to edit a product, which includes selecting a category that corresponds to the product. However, when I open the modal, the selected group/category is not displayed in the d ...