Generally we use regular expression to validate phone number which fails in many cases.  For example +91 9677146866 is the correct number which exists, +91 2677146866 is also correct number which doesn't exists. Our regular expression shows both as valid phone numbers. For accurate phone number validation, we will use google-libphonenumber library.

Phone number field with country code

Observe below image. Provide field for country code and number

Validating Phone number with google-libphonenumber

Import Utils from google-libphonenumber
import {PhoneNumberFormat, PhoneNumberUtil} from 'google-libphonenumber';

validatePhoneNumber(phoneNumber) {
  /*
  Phone number validation using google-libphonenumber
  */
  let valid = false;
  try {
    const phoneUtil = PhoneNumberUtil.getInstance();
    valid =  phoneUtil.isValidNumber(phoneUtil.parse(phoneNumber));
  } catch(e) {
    valid = false;
  }
  if(valid) {
    // do something
  } else {
    // do something
  }
}

Get Valid Phone number in international format

When save numbers in database, you better save them in single international format than many formats. Here is the piece of code which converts normal phone number to international format. 
getValidNumber(phoneNumber) {
  const phoneUtil = PhoneNumberUtil.getInstance();
  const parsedNumber = phoneUtil.parse(phoneNumber);
  return phoneUtil.format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)
}

CallingCodes.js

This file contains all country codes, which will be passed to react-select component as options
export default [
    {country : 'Afghanistan',   value : '93',   code : 'AF'},
    {country : 'Albania',   value : '355',  code : 'AL'},
    {country : 'Algeria',   value : '213',  code : 'DZ'},
    {country : 'American Samoa',    value : '1-684',    code : 'AS'},
    {country : 'Andorra',   value : '376',  code : 'AD'}
    .........
];
Using react-select component create Select component for selecting country code
<Select value={this.state.country} onChange={this.onSelect2} placeholder="country code"
               options={CallingCodes} labelKey="country" valueKey="value" valueRenderer={(country) => country.value}>
</Select>

Complete component code

import 'bootstrap/dist/css/bootstrap.min.css';
import 'react-select/dist/react-select.min.css';
import './phone-number.css';
import React from 'react';
import CallingCodes from './CallingCodes';
import {FormControl} from 'react-bootstrap';
import Select from 'react-select';
import {PhoneNumberFormat, PhoneNumberUtil} from 'google-libphonenumber';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      country:'',
      number:'',
      message:''
    }
    this.onChange = this.onChange.bind(this);
    this.onSelect2 = this.onSelect2.bind(this);
    this.validatePhoneNumber = this.validatePhoneNumber.bind(this);
  }

  onChange(event) {
    this.setState({
      number:event.target.value
    });
    this.validatePhoneNumber('+'+this.state.country+' '+event.target.value);
  }

  onSelect2(cntrObj) {
    this.setState({
      country:cntrObj.value
    });
    this.validatePhoneNumber('+'+cntrObj.value+' '+this.state.number);
  }

  validatePhoneNumber(phoneNumber) {
    /*
    Phone number validation using google-libphonenumber
    */
    let valid = false;
    try {
      const phoneUtil = PhoneNumberUtil.getInstance();
      valid =  phoneUtil.isValidNumber(phoneUtil.parse(phoneNumber));
    } catch(e) {
      valid = false;
    }
    if(valid) {
      this.setState({
        message:'Phone number '+this.getValidNumber(phoneNumber)+' is valid',
        color:'green'
      });
    } else {
      this.setState({
        message:'Phone number '+phoneNumber+' is not valid',
        color:'red'
      });
    }
  }

  getValidNumber(phoneNumber) {
    const phoneUtil = PhoneNumberUtil.getInstance();
    const parsedNumber = phoneUtil.parse(phoneNumber);
    return phoneUtil.format(parsedNumber, PhoneNumberFormat.INTERNATIONAL)
  }

  render() {
    return (
      <div>
        <h1>Phone number with country codes using ReactJS</h1>
        <div className="phone-number" style={{display:'flex'}}>
          <div className="phone-number--country">
            <Select value={this.state.country} onChange={this.onSelect2} placeholder="country code"
               options={CallingCodes} labelKey="country" valueKey="value" valueRenderer={(country) => country.value}>
            </Select>
          </div>
          <div className="phone-number--number">
            <FormControl value={this.state.number} onChange={this.onChange} placeholder="phone number">
            </FormControl>
          </div>
        </div>
        <div className="message" style={{color:this.state.color}}>
          {this.state.message}
        </div>
      </div>
    )
  }
}

85 comments:

  1. Hey Srinivas, nice post to validate country codes. This is perfect for sites that need offshore accounts to login internationally. Keep up the great work.

    ReplyDelete
  2. I have utilized Google on two or three events and discovered unlisted phone numbers that ended up being telemarketers. 0800 number cost

    ReplyDelete
  3. Usually these bills are so complex that it is difficult to find these extra lines. This brings me to a major difference in the new telephone systems.free business calls

    ReplyDelete
  4. The primary thing you need to do is to utilize a free inquiry, for example, the White Pagesfree-lookup.net

    ReplyDelete
  5. Awesome blog. I would love to see true life prepared to walk, so please share more informative updates. Great work keeps it up. PCNSE exam dumps

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. The blog is clear exhibition of the way that, you can bargain with the quality.
    online cell phone lookup reviews

    ReplyDelete
  8. This way, the phone can be tracked anywhere and anytime. However, these aforementioned microchips can be quite pricey, but are available online.localiser un portable gratuitement grace a son numero

    ReplyDelete
  9. Gone were the days that just private and government spies utilize invert telephone investigators. Family units, modern and business foundations, police and crisis reaction groups saw the incredible significance of having these basic telephone numbers query to guarantee that their callers and the circumstances are certifiable.https://www.techpally.com/private-call-announcer-apps/

    ReplyDelete
  10. Great post but I was wondering if you could write a little more on this subject? I’d be very thankful if you could elaborate a little bit further. Thanks in advance! Voyance par telephone

    ReplyDelete
  11. For the uninitiated, a cell phone is a cell phone which can associate with the web and can run and buy applications.oukitel k12

    ReplyDelete
  12. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. dan ca

    ReplyDelete
  13. I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. http://locateanumber.com

    ReplyDelete
  14. When your website or blog goes live for the first time, it is exciting. That is until you realize no one but you and your. legal entity identifier

    ReplyDelete
  15. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete
  16. Everyone loves it whenever people come together and share thoughts. Great site, stick with it!
    Tech news

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. A motivating discussion is definitely worth comment. There's no doubt that that you ought to write more about this subject matter, it may not be a taboo matter but generally views people do not talk about these topics. To the next! Best wishes!!

    ReplyDelete
  19. This is a topic that's near to my heart... free Take care! Exactly where are your contact details though?

    ReplyDelete
  20. The next time I read a blog, I hope that it does not fail me just as much as this particular technology one. I mean, I know it was my choice to read, nonetheless I actually believed you would probably have something useful to talk about. All I hear is a bunch of whining about something you could fix if you were not too busy looking for attention.

    ReplyDelete
  21. THE BEST AGENCY SERVING CLIENTS COUNTRYWIDE
    Located in Delhi, Webmarts is a professionally managed digital marketing agency offering a host of demanding services. We offer SEO services, web development, web designing, social media marketing, and more services to clients in different businesses.

    Best SEO Company in Delhi
    Best seo services in Delhi
    Best seo agency in Delhi
    Seo service in Delhi
    Seo service provider in Delhi
    Top rated seo service provider in Delhi
    Best seo company in Jankpuri
    Best seo company in uttamnagar
    Best seo company in Tilak nagar

    ReplyDelete
  22. ERP Gold Software
    How ERP Gold works as an inventory management software for Walmart
    Why do sellers on Walmart need inventory management software?
    Inventory management involves the process of ordering, handling, storing, and processing a company’s inventory. This has done because, without an effective inventory management system, the full potential of the supply chain becomes unattainable.
    For more information about ERP Gold inventory management software, please click on the link below.
    https://www.erp.gold/walmart-erp-integration-software/

    ReplyDelete
  23. This page contains the necessary information I have a enjoyable site if you feel free you can visit my site Yespornplease

    ReplyDelete
  24. This page contains the necessary information The Samsung Galaxy M52 is going to be published very soon if you feel free you can visit my site Samsung M52 Price

    ReplyDelete
  25. Thank you for sharing your info. I really appreciate your efforts and I am waiting for your further write ups thank you once again. And know Mimz International Merchandising Company provides services to clients to Make their Vision a Reality and to help companies to improve business performance. merchandising

    ReplyDelete
  26. Nice informative post. Thanks so much for sharing this awesome details.Retail Electricity Supplier

    ReplyDelete
  27. here you can get more information about joining pakistan navy
    https://joinpaknavy.site/

    ReplyDelete

  28. The post you have shared here is great. I really like and appreciate your work. The points you mentioned in this article are helpful. I have to try to follow these points and also share others.Baby Wipes Online UAE


    ReplyDelete
  29. Here you Provided really good information, really appreciate your efforts it. Properties in Udaipur and Affordable housing in Udaipur

    ReplyDelete
  30. I have tagged it to read some other time. Thanks so much and keep it up. CCleaner Pro Crack

    ReplyDelete
  31. I would like to say that this blog really convinced me to do it! Thanks, very good post. localisertel.com

    ReplyDelete
  32. You can contact me for a peaceful time frame, a proper Call Girls in Agra conference and even an occasion or a capacity; I will take a position right nearby and will complement and improve your area amongst the team. First of all hiring Escorts Service in Faridabad does not mean you will get infected with immune diseases. Our Agency is a genuine and trusted escort agency and provides a call girl who is educated and well mannered.
    Call Girls in Agra
    Call Girls

    ReplyDelete
  33. I must say that this is a post enriched with information, stylistics, strategies and so on. I usually follow your post structure which eventually helps me in my writing on Our Website 1 & Our Website 2given here. We spread rapid yet authentic news throughout the world. Thanks a lot for this post. See recent events from the following:
    1.RU A-unit Question Solution
    2.2021 DSHE Assignment syllabus class 6-9
    3.New High School Assignment 2021

    ReplyDelete
  34. Wow thanks so much for this inspiring and motivating article. Bitcoin Private Key Recovery. We guide you on how to recover lost funds in your bitcoin wallet, recover hacked/stolen accounts, spend non-spendable funds and other issues with your block-chain wallets.
    Kindly visit our website by clicking the link below and feel free to give us a message for more information, we are highly recommended and totally safe to work with our English, Indian and American tech wizards world-wide visit us
    at bestbitcoinprivatekeyrecovery.org
    Or contact us on WhatsApp +1 903 600 570

    ReplyDelete
  35. Nice trick, will be coming very handy. Do check below you might be able to find something very helpful for your business.
    buy logo

    ReplyDelete
  36. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information... 안전놀이터목록

    ReplyDelete
  37. "Greetings! Very useful advice within this article!
    It’s the little changes which will make the largest changes.
    Many thanks for sharing!" 사설토토

    ReplyDelete
  38. There is a lot of information here that can help any business get started with a successful social networking campaign 먹튀검증커뮤니티

    ReplyDelete
  39. Very energetic blog, I liked that bit. 꽁머니홍보

    ReplyDelete
  40. I am very happy after visiting your website with very useful information. I am from one of the digital marketing agency... To visit my agency click on link Visitdigitalguru

    ReplyDelete
  41. When I read an article on this topic, 온라인바둑이 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

    ReplyDelete
  42. Attractive section of content. I simply stumbled upon your blog and in accession capital to assert that I acquire in fact enjoyed
    account your blog posts. Anyway I’ll be subscribing
    on your augment or even I success you access constantly quickly.오피사이트

    ReplyDelete
  43. Thanks for sharing information with us…satisfied after visiting your blog…. Learn the latest trends & their practical application by experts with us…you can contact us click on
    Visit ISMT India

    ReplyDelete
  44. I’m not sure exactly why but this weblog is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists. 안전놀이터순위

    ReplyDelete
  45. Hello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 토토사이트

    ReplyDelete
  46. Admiring the dedication you put into your site and in depth information you offer. It's awesome to come across a blog 먹튀검증사이트 every once in a while that isn't the same unwanted rehashed material. Fantastic read! I've saved your site and I'm including your RSS feeds to my Google account.

    ReplyDelete
  47. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea! 메이저놀이터

    ReplyDelete
  48. As soon as I noticed this internet site I went on reddit to share some of the love with them. 먹튀

    ReplyDelete
  49. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea. 온라인포커

    ReplyDelete
  50. Someone necessarily help to make severely articles I might state. That is the first time I frequented your web page and up to now? I surprised with the analysis you made to create this actual publish extraordinary. Fantastic process 안전놀이터

    ReplyDelete
  51. Through www.amazon.com/mytv - how you can connect your mobile phone to Amazon Prime. Through amazon.com/mytv, you can watch your favorite TV shows, series movies. You can watch prime videos anywhere on your device. Users need to create an Amazon account if they don’t have an Amazon account and enter the Amazon my TV activation code to watch Amazon prime videos on your device.

    amazon.com/mytv | www.amazon.com/mytv

    ReplyDelete
  52. Study Engineering at the best autonomous college in AP with scholarships and full faculty support with high quality education and professional career support.
    https://www.adityatekkali.edu.in/

    ReplyDelete
  53. Someone necessarily help to make severely articles I might state. That is the first time I frequented your web page and up to now? I surprised with the analysis you made to create this actual publish extraordinary. Fantastic process 안전놀이터

    ReplyDelete
  54. ou need to be a part of a contest for one of the highest quality sites on the 토토사이트. I most certainly will recommend this site!

    ReplyDelete
  55. Someone necessarily help to make severely articles I might state. That is the first time I frequented your web page and up to now? I surprised with the analysis you made to create this actual publish extraordinary. Fantastic process 안전놀이터

    ReplyDelete
  56. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts. 스포츠토토사이트

    ReplyDelete
  57. Of course, your article is good enough, but I thought it would be much better to see professional photos and videos together. There are articles and photos on these topics on my homepage, so please visit and share your opinions. 토토커뮤니티

    ReplyDelete
  58. Thanks for writing this awesome 메이저사이트. I'm a long time reader but I've never been compelled to leave a comment. I subscribed to your blog and shared this on my Facebook. Thanks again for a great article!

    ReplyDelete
  59. We are looking for a lot of data on this item. In the meantime, this is the perfect article I was looking for . Please post a lot about items related to 메이저놀이터추천 !!! I am waiting for your article. And when you are having difficulty writing articles, I think you can get a lot of help by visiting my .

    ReplyDelete
  60. We are looking for a lot of data on this item. In the meantime, this is the perfect article I am very glad to read it.
    https://thirdconditional124.blogspot.com/2021/07/blog-post.html

    ReplyDelete
  61. I love what you 메이저놀이터 tend to be up too. This kind of clever work and exposure! Keep up the excellent works guys I've incorporated you guys to our blogroll.

    ReplyDelete
  62. As I am looking at your writing, Bóng độ I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.

    ReplyDelete
  63. As I am looking at your writing, I regret being unable to do outdoor activities due to Corona 19, and I miss my old daily life. If you also miss the daily life of those days, would you please visit my site once? My site is a site where I post about photos and daily life when I was free.먹튀사이트

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts