Vee-validate: Phone number validation rule

Created on 15 Sep 2017  路  8Comments  路  Source: logaretm/vee-validate

Any plans for adding phone number validation? It would be very cool.

request

Most helpful comment

Thanks @XXiphias and @the94air. For everyone who's gonna see this github issue, here's how it might look like when using webpack:

import { Validator } from 'vee-validate';
import PhoneNumber from 'awesome-phonenumber'

const phoneNumber = {
  getMessage: field => `${field} is not a valid phone number`,
  validate (value) {
    return new Promise(resolve => {
      let phone = new PhoneNumber(value);
      resolve({ valid: phone.isValid() })
    })
  }
}
Validator.extend('phoneNumber', phoneNumber)

All 8 comments

How would this validation be done? I liked the idea, but in different countries how would that difference be?

It would actually be a pain to cover all scenarios, for example regions and their prefixes across the world. Your app may not target countries like Egypt for example so you don't care about their prefixes, but vee-validate cannot make such assumptions. so its not really a general case.

Luckily you can create your own custom rules, there are validators that support such functionality out there like validator.js which has a isMobilePhone validator.

https://github.com/chriso/validator.js

Still in the future who knows, it could be included if the need arises.

A simple regex rule that allows an optional '+' at the start and numbers would be a plus :)

To remove the work of handling each regions formatting, Google's libphonenumber library could be used as a dependency to validate phone numbers. You just need to find a way to pass in an argument with the country code to the library. Although, it would practically do all of the validation work so it might be pointless to roll that into Vee-Validate when it can be used separately easily enough.

Here's a cleaner implementation of the library for anyone who wants a phone number validator: https://www.npmjs.com/package/awesome-phonenumber

Thanks @XXiphias for sharing the solution with us. The point of power that you just need an input and you are done.

let PhoneNumber = require( 'awesome-phonenumber' );

let pn = new PhoneNumber('+441618811234');

console.log(pn.isValid()); // true
console.log(pn.getRegionCode()); // "GB"

Thanks @XXiphias and @the94air. For everyone who's gonna see this github issue, here's how it might look like when using webpack:

import { Validator } from 'vee-validate';
import PhoneNumber from 'awesome-phonenumber'

const phoneNumber = {
  getMessage: field => `${field} is not a valid phone number`,
  validate (value) {
    return new Promise(resolve => {
      let phone = new PhoneNumber(value);
      resolve({ valid: phone.isValid() })
    })
  }
}
Validator.extend('phoneNumber', phoneNumber)

For v3:

extend('phone', {
    message (fieldName) {
        return `${fieldName} is not a valid phone number`;
    },
    validate (value) {
        return new Promise(resolve => {
            let phone = new PhoneNumber(value);
            resolve({ valid: phone.isValid() })
        });
    }
});

with google lib phone & vee-validate v3

// validateLogic.js file.
import {
  PhoneNumberUtil,
  PhoneNumberFormat as PNF,
} from 'google-libphonenumber';

export default function (value, alpahCode) {
  if (!value || value.length === 0) {
    return;
  }
  const phoneUtil = PhoneNumberUtil.getInstance();

  const number = phoneUtil.parse(value, alpahCode);
  //   check with country code isValidNumber

  console.log(phoneUtil.format(number, PNF.INTERNATIONAL));

  if (phoneUtil.isValidNumber(number, alpahCode)) {
    return true;
  } else {
    return false;
  }
}

create rule

// vee-validate.js file 
import { extend } from 'vee-validate';
import validator from './validateLogic';

extend('mobileNumber', {
  params: ['code'],
  validate(value, { code }) {
    let telResult;
      telResult = validator(value, code);
      return telResult;
  },
});

Use Rules:

     <ValidationProvider
         :rules="{
          required: true,
           numeric: true,
            mobileNumber: { code: `IR` },
          }"
         :name="mobile"
       >
             // your input 
       </ValidationProvider>
Was this page helpful?
0 / 5 - 0 ratings