How can vee-validate validates email and phone at the same time How can vee-validate validates email and phone at the same time vue.js vue.js

How can vee-validate validates email and phone at the same time


The issue that you're running into is that VeeValidate rules are all AND based; what this means is that 'required|email|phone' is checking to see if the username field has a value AND it's an email AND it's a phone number.

To solve your problem, you'll want to use a completely custom rule alongside the required rule. This can be accomplished in the following way:

const phoneOrEmailRule = {  getMessage(field, args) {    return `The ${field} must be either a valid phone number or e-mail`;  },  validate(value, args) {    // Custom regex for a phone number     const MOBILEREG = /^((1[3578][0-9])+\d{8})$/;    // Check for either of these to return true    return VeeValidate.Rules.email(value) || MOBILEREG.test(value);  }};

Once you've created your rule, you'll need to add it to the VeeValidate validator.

VeeValidate.Validator.extend('phoneOrEmail', phoneOrEmailRule);

Afterwards, you can add it to a field.

  <input type="text" name="username" v-model="username" class="username" v-validate="'required|phoneOrEmail'">

Here's a CodePen that shows how it looks when it's working. For testing, you can use any valid email that passes VeeValidate's normal email rule; when it comes to the phone number, it will be based off your regex so a value like 13112345678 would succeed.