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

1 comment:

  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

Blogroll

Follow this blog by Email

Popular Posts