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>
    )
  }
}

78 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. Everyone loves it whenever people come together and share thoughts. Great site, stick with it!
    Tech news

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

    ReplyDelete
  17. 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
  18. This is a topic that's near to my heart... free Take care! Exactly where are your contact details though?

    ReplyDelete
  19. 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
  20. 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
  21. This page contains the necessary information I have a enjoyable site if you feel free you can visit my site Yespornplease

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

    ReplyDelete

  23. 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
  24. Here you Provided really good information, really appreciate your efforts it. Properties in Udaipur and Affordable housing in Udaipur

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

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

    ReplyDelete
  27. 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
  28. 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
  29. 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
  30. This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information... 안전놀이터목록

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

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

    ReplyDelete
  33. 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
  34. 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
  35. This is the perfect post.안전놀이터 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.


    ReplyDelete
  36. That's a really impressive new idea! 안전한놀이터 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.


    ReplyDelete
  37. Thanks for an interesting blog. What else may I get that sort of info written in such a perfect approach? I have an undertaking that I am just now operating on, and I have been on the lookout for such info 먹튀검증 It's amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you.


    ReplyDelete
  38. I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot! Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog First You got a great blog .I will be interested in more similar topics. i see you got really very useful topics, i will be always checking your blog thanks. Excellent effort to make this blog more wonderful and attractive. Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. 먹튀사이트

    ReplyDelete
  39. Thanks for sharing. And also this article gives the mild wherein we are able to have a look at the truth. That is very quality one and offers indepth statistics. Thank you for this fine article… its a extraordinary pleasure analyzing your put up. Its full of statistics i'm seeking out and i love to put up a remark that "the content material of your post is awesome" remarkable paintings. Thank you for each other informative net web page. Where else may want to i am getting that sort of records written in this sort of best manner? I’ve a task that i'm really now working on, and i've been on the look out for such info. Perhaps that is a piece offf subject matter however in any case, i have been browsing approximately your weblog and it looks surely neat. Impassioned approximately your writing. I am creating a new weblog and tough-pressed to make it seem wonderful, and supply extraordinary articles. I have located plenty on your web site and that i sit up for additional updates and could be again. Introductory you acquire a tremendous blog . I warranty be engaged with further to uniform mins. 헤이먹튀

    ReplyDelete
  40. I found your this post while searching for some related information on blog search...Its a good post..keep posting and update the information. Love to read it,Waiting For More new Update and I Already Read your Recent Post its Great Thanks. This is very informative and you are obviously very knowledgeable in this area. You will find a lot of approaches after visiting your post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Thanks for sharing. This is a fabulous post I seen because of offer it. It is really what I expected to see trust in future you will continue in sharing such a mind boggling post. 토토안전센터

    ReplyDelete
  41. I simply couldn’t go away your website before suggesting that I actually enjoyed the standard information an individual provide on your visitors? Is gonna be back frequently in order to inspect new posts. I found your blog via Google while searching for first aid for a heart attack and your post looks very interesting for me. This is my first visit to your blog! We are a team of volunteers and starting a new project in a community in the same niche. Great post however , I was wanting to know if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit further. Bless you! 먹튀폴리스

    ReplyDelete
  42. hey there, i do suppose your weblog should in all likelihood be having internet browser compatibility problems. On every occasion i check your weblog in safari, it appears best but whilst beginning in net explorer, it has some overlapping problems. I sincerely desired to give you a short heads up! Besides that, excellent blog! I am glad to read your blog. your blog is really awesome and cool. your blog is really great and cool. thanks for sharing the nice and cool post . I have been searching to find a comfort or effective procedure to complete this process and I think this is the most suitable way to do it effectively. 카이소

    ReplyDelete
  43. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. Writing with style and getting good compliments on the article is quite hard, to be honest.But you've done it so calmly and with so cool feeling and you've nailed the job. This article is possessed with style and I am giving good compliment. Best! It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it! 먹튀연구실

    ReplyDelete
  44. I read a super deal of stuff and i discovered that the technique for keeping in touch with clearifing that precisely need to state became brilliant so i am stimulated and ilike to return again again in destiny.. Beneficial information .. I'm very satisfied to examine this text.. Thanks for giving us this useful records. Brilliant walk-via. I recognize this post. Such an specifically large article. To a exceptional degree charming to look at this article. I ought to want to thanks for the undertakings you had made for growing this extraordinary article . High-quality blog. I took delight in scrutinizing your articles. This is extraordinarily a top notch scrutinized for me. I have bookmarked it and i'm suspecting scrutinizing new articles. Retain doing excellent! I experience extremely cheerful to have visible your site page and count on this type of huge wide variety of all of the extra engaging situations perusing right here. Tons favored another time for every one of the points of hobby. i need you to thank in your season of this high-quality study!!! I definately recognize each and every piece of it and that i have you bookmarked to examine new stuff of your blog an unquestionable requirement read blog! 토토지식백과 토토지식백과

    ReplyDelete
  45. Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing. Really awesome! I like the site, I really like this topic. Giving a lot of good news and knowledge. Thank you for the information. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. 카지노마트

    ReplyDelete
  46. Youre so cool! I dont suppose Ive read something like this before. So good to find someone with some authentic ideas on this subject. realy thanks for starting this up. this website is one thing that is wanted on the net, somebody with a little originality. helpful job for bringing one thing new to the web! I really like your writing so a lot! percentage we keep up a correspondence extra about your article on AOL? I require an expert on this area to unravel my problem. Maybe that's you! Taking a look ahead to look you. I want to say thanks to you. I have bookmark your site for future updates. I think I have never seen such blogs ever before that has complete things with all details which I want. So kindly update this ever for us. 해외배팅사이트

    ReplyDelete
  47. I was impressed by your writing. Your writing is impressive. I want to write like you.안전놀이터 I hope you can read my post and let me know what to modify. My writing is in I would like you to visit my blog.


    ReplyDelete
  48. When I read your article on this topic, the first thought seems profound and difficult. There is also a bulletin board for discussion of articles and photos similar to this topic on my site, but I would like to visit once when I have time to discuss this topic. sòng bạc


    ReplyDelete
  49. You made some good points there. I did a Google search about the topic and found most people will believe your blog. 메리트카지노


    ReplyDelete
  50. I am a fan of reading to add insight to information. Thank you for this great blog. this is here, the few months I am visiting and following you. What I really like about you is that your writing style. 야설

    ReplyDelete
  51. I found your blog while I was webs writing to find the above information. Your writing has helped me a lot. I'll write a nice post by quoting your post.
    일본야동

    ReplyDelete
  52. Hi there, I simply hopped over in your website by way of StumbleUpon. Now not one thing I’d typically learn, but I favored your emotions none the less. Thank you for making something worth reading. 먹튀검증


    ReplyDelete
  53. I was impressed by your writing. Your writing is impressive. I want to write like you.우리카지노 I hope you can read my post and let me know what to modify. My writing is in I would like you to visit my blog.


    ReplyDelete
  54. I accidentally searched and visited your site. I still saw several posts during my visit, but the text was neat and readable. I will quote this post and post it on my blog. Would you like to visit my blog later? keonha cai


    ReplyDelete
  55. I don’t think many of websites provide this type of information. 에볼루션바카라

    ReplyDelete
  56. Everything is very open with a precise explanation of the issues.
    It was really informative. 스포츠중계 Your website is useful. Thank
    you for sharing!

    ReplyDelete
  57. Your post is very helpful and information is reliable. I am satisfied with your post. Thank you so much for sharing this wonderful postDigital Marketing Course

    ReplyDelete


  58. Thanks for sharing with us this important Content.
    슬롯사이트

    found exactly what I used to be having a look for.
    슬롯사이트

    ReplyDelete
  59. I get pleasure from, cause I found just what I used to be having a look for.
    You’ve ended my four day long hunt! God Bless you man. Have a nice day.

    카지노사이트

    ReplyDelete
  60. Shoes with comfort and style are hard to come by. Servis PK Online offers a collection of shoes for women which can be used for any occasion. Buy online women shoes, Sandals, Chappals, Casual Wear Shoes, Heels, Pump Shoes in various Colours at reasonable Price from Servis Pk. We can deliver in all Metro cities across Pakistan, like Lahore, Karachi, and Islamabad.

    ReplyDelete
  61. Great article!! I am also using drop my link, it is very helpful in making back links.Digital Signature in Gurgaon

    ReplyDelete
  62. The article on phone numbers with country codes is a valuable resource. It provides essential information for individuals dealing with international communication or travel. Understanding country codes ensures efficient and error-free dialing. This article simplifies the process and is a handy reference for anyone navigating global connections.

    ReplyDelete
  63. A debt of gratitude is in order for sharing great data, you may as of now have a site yet you aren't sure in the event that it is really bringing you organizations. Detective Agency in Delhi

    ReplyDelete

Blogroll

Popular Posts