I have write a custom validator for phone and use it like this
<template>
<input type="text" name="username" class="username" v-validate="'required|email|phone'">
</template>
<script>
import { MobileValidate } from '@/validates/MobileValidates'
Validator.extend('phone', MobileValidate);
</script>
const MOBILEREG = /^((1[3578][0-9])+\d{8})$/;
export const MobileValidate = {
getMessage(field, args) {
return 'phone is wrong';
},
validate(value, args) {
console.log(MOBILEREG.test(value), value)
return MOBILEREG.test(value);
}
};
I want to validate the username is email or phone number, but it seems not work. How can I solve this problem?
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.