Search code examples
javascriptregexvue.jsvuelidate

How do I check two regex values with vuelidate


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

Solution

  • 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