How do I check two regex values with vuelidate

10.8k views Asked by At

I'm trying to validate an input field with vuelidate. I need it to return valid if either of the following regular expressions 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
    },

How do I get this to work?

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) 
    },

Solution 2

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

Validation

checkvals: {
      required,
      numeric,
      numbercheck,
    },
2

There are 2 answers

0
The fourth bird On BEST ANSWER

Instead of using a conditional operator, you could also use a single pattern by placing 7(\D*\d){12} and 1(\D*\d)11} in an alternation, as the start and the end of the pattern are the same.

If you don't need the value of the capturing group afterwards, you can turn it in to a non capturing one using (?:

I suspect that in the second part, this 11} should be a quantifier like {11}

The pattern could look like:

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

Explanation

  • ^\D* Start of string and match 0+ non digits
  • (?: Non capture group for the alternation
    • 7(?:\D*\d){12} Match 7 and 12 digits separated by optional non digits
    • | Or
    • 1(?:\D*\d){11} Match 1 and 11 digits separated by optional non digits
  • ) Close non capture group
  • \D*$ Match optional non digits and assert the end of the string

See a regex demo

0
Shylaja Haridas On

I'm aware this is an old answer but with the latest @vuelidate/validators: 2.0.4 we no longer need to import it from 'vuelidate/lib/validators'. It throws

Failed to resolve import "vuelidate/lib/validators"

You can import it as such

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

Hope this helps someone.