Reputation: 387
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,
},
Upvotes: 4
Views: 11177
Reputation: 1
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.
Upvotes: 0
Reputation: 163467
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|
Or1(?:\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 stringSee a regex demo
Upvotes: 1