phone validator

Validate a phone number

Options

Using with form field
The HTML attributes are used to set the validator options via the Declarative plugin
(* denotes a required option)
NameHTML attributeTypeDescription
country *data-fv-phone___countryString or FunctionAn ISO-3166 country code
messagedata-fv-phone___messageStringThe error message
Since the plugin doesn't support HTML 5 type="tel" attribute, you should use type="text" instead
If you want to support custom formats of a phone number, you should use the Transformer plugin.
The validator supports the following countries:
CountryCountry code
United StatesUS
United Arab EmiratesAE
BulgariaBG
BrazilBR
ChinaCN
Czech RepublicCZ
DenmarkDK
FranceFR
GermanyDE
IndiaIN
MoroccoMA
NetherlandsNL
PakistanPK
RomaniaRO
RussiaRU
SlovakiaSK
SpainES
ThailandTH
United KingdomGB
VenezuelaVE
Using the ES6 module
// You might need to change the importing path
import { phone } from '/vendors/@form-validation/cjs/validator-phone';
const result = phone().validate({
value: ...,
options: {
// Can be a string or a function returns a string
country: ...,
message: ...,
},
});
/*
result is an object of
{
valid: true or false,
message: The error message
}
*/
Using the npm package
  • Install the validator package:
$ npm install @form-validation/validator-phone
  • Use the phone validator:
import { phone } from '@form-validation/validator-phone';
const result = phone().validate({
value: ...,
options: {
// Can be a string or a function returns a string
country: ...,
message: ...,
},
});

Basic example

phone validator

NPM package example

The following snippet shows how to use the phone validator with the npm package:
import { phone } from '@form-validation/validator-phone';
const res1 = phone().validate({
value: '246.555.8888',
options: {
country: 'US',
message: 'The value is not a valid phone number',
},
});
// res1.valid === true
const res2 = phone().validate({
value: '(+55) 15 3702-7523',
options: {
country: 'BR',
message: 'The value is not a valid phone number',
},
});
// res2.valid === true

See also

Changelog

v2.1.0
  • The validator doesn't work properly if the message property isn't defined
v2.0.0
  • Add the npm package
v1.6.0
  • Fixed an issue that the country option isn't passed to the placeholder message