react-phone-input-2

A react component to format phone numbers

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
react-phone-input-2
2.15.12 years ago7 years agoMinified + gzip package size for react-phone-input-2 in KB

Readme

React-Phone-Input-2

DONATIONS / FUNDING NEEDED

bitcoin bc1qa7q6gf9e06ssqrc46j5lekq886rlyyk6sdhjj0
ethereum 0x2b9429a7362a9b14f3d84a408d33caab29bdc225
Highly customizable phone input component with auto formatting.
npm version
npm downloads PRs Welcome travis build
animation

Installation

```shell-script npm install react-phone-input-2 --save
## Usage
```jsx
import PhoneInput from 'react-phone-input-2'
import 'react-phone-input-2/lib/style.css'

<PhoneInput
  country={'us'}
  value={this.state.phone}
  onChange={phone => this.setState({ phone })}
/>
available styles - style • high-res • material • bootstrap • semantic-ui • plain

Demo 1 (UI) - Demo 2 (CSS)

screenshot

Options

<th> Name </th>
<th> Type </th>
<th> Description </th>
<th> Example </th>
<td> country </td>
<td> string </td>
<td> initial country </td>
<td> 'us' | 1 </td>
<td> value </td>
<td> string </td>
<td colspan="2"> input state value </td>

<td> onlyCountries </td>
<td> array </td>
<td> country codes to be included </td>
<td> ['cu','cw','kz'] </td>
<td> preferredCountries </td>
<td> array </td>
<td> country codes to be at the top </td>
<td> ['cu','cw','kz'] </td>
<td> excludeCountries </td>
<td> array </td>
<td> array of country codes to be excluded </td>
<td> ['cu','cw','kz'] </td>

<td> placeholder </td>
<td> string </td>
<td colspan="2"> custom placeholder </td>

<td> inputProps </td>
<td> object </td>
<td colspan="2"> props to pass into the input </td>

<th> Booleans </th>
<th> Default </th>
<th> Description </th>
<td> autoFormat </td>
<td> true </td>
<td> on/off phone formatting </td>
<td> disabled </td>
<td> false </td>
<td> disable input and dropdown </td>
<td> disableDropdown </td>
<td> false </td>
<td> disable dropdown only </td>
<td> disableCountryCode </td>
<td> false </td>
<td> </td>
<td> enableAreaCodes </td>
<td> false </td>
<td> enable local codes for all countries </td>
<td> enableTerritories </td>
<td> false </td>
<td> enable dependent territories with population of ~100,000 or lower </td>
<td> enableLongNumbers </td>
<td> false </td>
<td> boolean/number </td>
<td> countryCodeEditable </td>
<td> true </td>
<td> </td>
<td> enableSearch </td>
<td> false </td>
<td> enable search in the dropdown </td>
<td> disableSearchIcon </td>
<td> false </td>
<td> hide icon for the search field </td>

<PhoneInput
  inputProps={{
    name: 'phone',
    required: true,
    autoFocus: true
  }}
/>

Contents

- Phone without dialCode - Check validity of the phone number - CDN

Style

<td> containerClass </td>
<td> string </td>
<td colspan="2"> class for container </td>
<td> inputClass </td>
<td> string </td>
<td colspan="2"> class for input </td>
<td> buttonClass </td>
<td> string </td>
<td colspan="2"> class for dropdown button </td>
<td> dropdownClass </td>
<td> string </td>
<td colspan="2"> class for dropdown container </td>
<td> searchClass </td>
<td> string </td>
<td colspan="2"> class for search field </td>

<td> containerStyle </td>
<td> object </td>
<td colspan="2"> styles for container </td>
<td> inputStyle </td>
<td> object </td>
<td colspan="2"> styles for input </td>
<td> buttonStyle </td>
<td> object </td>
<td colspan="2"> styles for dropdown button </td>
<td> dropdownStyle </td>
<td> object </td>
<td colspan="2"> styles for dropdown container </td>
<td> searchStyle </td>
<td> object </td>
<td colspan="2"> styles for search field </td>

Events

<td> onChange </td>
<td> onFocus </td>
<td> onBlur </td>
<td> onClick </td>
<td> onKeyDown </td>

onChange(value, country, e, formattedValue)
Country data object not returns from onKeyDown event
<th> Data </th>
<th> Type </th>
<th> Description </th>
<td> value/event </td>
<td> string/object </td>
<td> event or the phone number </td>
<td> country data </td>
<td> object </td>
<td> country object { name, dialCode, countryCode (iso2) } </td>

Regions

<th> Name </th>
<th> Type </th>
<th> Description </th>
<td> regions </td>
<td> array/string </td>
<td> to show countries only from specified regions </td>

<th> Regions </th>
<td> ['america', 'europe', 'asia', 'oceania', 'africa'] </td>
<th> Subregions </th>
<td> ['north-america', 'south-america', 'central-america', 'carribean', 'eu-union', 'ex-ussr', 'ex-yugos', 'baltic', 'middle-east', 'north-africa'] </td>

<PhoneInput
  country='de'
  regions={'europe'}
/>

<PhoneInput
  country='us'
  regions={['north-america', 'carribean']}
/>

Predefined localization

es Spanish, de Deutsch, ru Russian, fr French
jp Japanese, cn Chinese, pt Portuguese, it Italian
ir Iranian, ar Arabic, tr Turkish, id Indonesian
hu Hungarian, pl Polish, ko Korean
import es from 'react-phone-input-2/lang/es.json'

<PhoneInput
  localization={es}
/>

Local area codes

<PhoneInput
  enableAreaCodes={true}
  enableAreaCodes={['us', 'ca']}
  enableAreaCodeStretch
/>

Flexible mask

If enableAreaCodeStretch is added, the part of the mask with the area code will not stretch to length of the respective section of phone mask. Example: +61 (2), +61 (02)

Custom masks

<PhoneInput
  onlyCountries={['fr', 'at']}
  masks={{fr: '(...) ..-..-..', at: '(....) ...-....'}}
/>

Custom area codes

<PhoneInput
  onlyCountries={['gr', 'fr', 'us']}
  areaCodes={{gr: ['2694', '2647'], fr: ['369', '463'], us: ['300']}}
/>

Other props

<td> defaultMask </td>
<td> ... ... ... ... .. </td>
<td> alwaysDefaultMask </td>
<td> false </td>
<td> prefix </td>
<td> + </td>
<td> searchPlaceholder </td>
<td> 'search' </td>
<td> searchNotFound </td>
<td> 'No entries to show' </td>

<td> copyNumbersOnly </td>
<td> true </td>
<td> renderStringAsFlag </td>
<td> string </td>
<td> autocompleteSearch </td>
<td> false </td>
<td> jumpCursorToEnd </td>
<td> false </td>
<td> priority </td>
<td> {{ca: 0, us: 1, kz: 0, ru: 1}} </td>
<td> enableClickOutside </td>
<td> true </td>
<td> showDropdown </td>
<td> false </td>
<td> defaultErrorMessage </td>
<td> string </td>
<td> specialLabel </td>
<td> string </td>
<td> disableInitialCountryGuess </td>
<td> false </td>
<td> disableCountryGuess </td>
<td> false </td>

Custom localization

<PhoneInput
  onlyCountries={['de', 'es']}
  localization={{de: 'Deutschland', es: 'España'}}
/>

<PhoneInput
  onlyCountries={['de', 'es']}
  localization={{'Germany': 'Deutschland', 'Spain': 'España'}}
/>

Preserve countries order

<PhoneInput
  onlyCountries={['fr', 'at']}
  preserveOrder={['onlyCountries', 'preferredCountries']}
/>

Guides

Phone without dialCode

handleOnChange(value, data, event, formattedValue) {
  this.setState({ rawPhone: value.slice(data.dialCode.length) })
}

Check validity of the phone number

isValid(value, country, countries, hiddenAreaCodes)
<PhoneInput
  isValid={(value, country) => {
    if (value.match(/12345/)) {
      return 'Invalid value: '+value+', '+country.name;
    } else if (value.match(/1234/)) {
      return false;
    } else {
      return true;
    }
  }}
/>

import startsWith from 'lodash.startswith';

<PhoneInput
  isValid={(inputNumber, country, countries) => {
    return countries.some((country) => {
      return startsWith(inputNumber, country.dialCode) || startsWith(country.dialCode, inputNumber);
    });
  }}
/>

Clear country

To clear country, pass null as value.

Dynamic placeholder

Show
const phoneCountryFormat = useMemo(() => phoneCountry?.format || undefined, [phoneCountry]);
const placeholder = useMemo(() => {
  if (phoneCountryFormat) {
    const words = phoneCountryFormat.split(' ');
    words.shift(); // I'm using only local numbers so here I remove the country code from the format
    let text = words.join(' ');
     // first digit is special on french numbers, these 3 lines could be removed
    if (country === 'fr') {
      text = text.replace('.', '6');
    }
    while (text.indexOf('.') > -1) {
      text = text.replace('.', `${Math.min(9, Math.max(1, Math.floor(Math.random() * 10)))}`);
    }
    return text;
  }
  return '';
}, [phoneCountryFormat, country]);

CDN

<script src="https://unpkg.com/react-phone-input-2@2.x/dist/lib.js"></script>

Contributing

  • Code style changes not allowed
  • Do not create issues about incorrect or missing country masks (of already present countries) or absent area codes (they will be closed). Only create issues if the subject is an actual mechanism that is not present in the component. Otherwise create a PR with a link that proves the correctness of your newly suggested mask or list of area codes
  • Do not send new languages

License

GitHub license
Based on react-phone-input
Make sure you donated for lib maintenance Donate