最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to limited the countries list in npm react-phone-number-input package - Stack Overflow

programmeradmin10浏览0评论

when react-phone-number-input use this npm package i want to allow limited countries show in dropdown if user enter other country which is not in list it display error not allow this country there is no prop where i limit the countries

when react-phone-number-input use this npm package i want to allow limited countries show in dropdown if user enter other country which is not in list it display error not allow this country there is no prop where i limit the countries

Share Improve this question edited May 22, 2019 at 4:36 Hamza Mazhar asked May 15, 2019 at 9:27 Hamza MazharHamza Mazhar 311 silver badge7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

If you take a look at the docs here you'll see you can add a countries prop to the ponent, and provide it with an array of strings. Their example shows this array:

["RU", "UA", "KZ"]

This would limit the list of countries to just those 3.

We can use the prop countryPickerProps

<PhoneInput
  countryPickerProps={{
    countryCodes: ['IN', 'GB', 'US'],
  }}
/>

Build a custom array of countries and then use the parseNumber function from libphonenumber-js library and get the country code from the user input number and pare it of your country list

To achieve this first create list of countries that you want to show in dropdown. Then on Blur run the validation if you want.

const whitelisted_conutries = ['WS',  'SB',  'TK',  'TO',  'TV',  'VU',  'WF',  'HK']:

then pass this to countries prop of PhoneInput like so,

import { isValidPhoneNumber } from 'react-phone-number-input';

      <PhoneInput
       defaultCountry="GB"
       flagUrl={'https://flag.pk/flags/4x3/{xx}.svg'}
       countries={whitelist}
       value={phone}
       onChange={(phone) => setState({ phone })}
       onBlur={() =>
       setState({
              hasEnterPhone: true,
              error: {
                ...error,
                phone: !phone
                  ? ''
                  : !isValidPhoneNo(phone) &&
                    'Please enter a valid mobile phone number.',
              },
            })
          }
        />

For more info on supported props refer developers docs tagged by @jamie in thread: Docs

发布评论

评论列表(0)

  1. 暂无评论