JavaScript Code to Validate Phone Number Input Based on Country (How to use libphonenumber in few steps)

While I was working on a submit form built using HubSpot marketing forms and templates. The client requested to validate the phone number field based on the selected country code. For instance, if user choose France for country code then there should be 9 digits in the phone number, so the number of digits and format should be validated according to the selected country code. 

Here is a screenshot of the form:

I tried many solutions but the best approach was to use an online API that can validate the phone number. Therefore I used the JavaScript library "libphonenumber". I added a reference to this library in the head section of the template:
<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/1.9.19/libphonenumber-js.min.js"></script>

Then I implemented a function to format the phone number and validate it based on the selected country. Here is the JavaScript code:

$(function() {
  setTimeout(function(){ 
    $('input[id^=phone]').keyup(function(event){
      ValidatePhoneNumberByCountry($(this));
    });
    $('input[type=submit]').on("click",function(e) {
      var ctrl = $('input[id^=phone]');
      var formIsValid = ValidatePhoneNumberByCountry($(ctrl));
      if (!formIsValid) {
         e.preventDefault();
       }
    });
  }, 2000);
  function ValidatePhoneNumberByCountry(ctrl) {
      var selectedCountry = $('select[id^=phone]').val();
      var val_old = $(ctrl).val();
      var newString = new libphonenumber.AsYouType(selectedCountry).input(val_old);
      $(ctrl).focus().val('').val(newString);
      var isValid = libphonenumber.isValidNumber($(ctrl).val(), selectedCountry);
      console.log(isValid);
      if(!isValid) {
           $('#errorMsg').remove();
           $('div[data-reactid=".hbspt-forms-0.1:$5"]').append("<div id=\"errorMsg\">Please provide valid phone number.</div>" );
      }
      else {
           $('#errorMsg').remove();
      }
      return isValid;
  }
});

In the function "ValidatePhoneNumberByCountry", I'm using "AsYouType" to format the input field then validating it. Then, I'm returning a flag to indicate if the phone number is valid or not along with displaying a validation message to inform the user that he must provide a valid phone number.

Also, I attached an event handler "onclick" to the submit button to force triggering the validation mechanism for this input field. 

This code can be used even outside HubSpot. For instance, you can use it in an ASP.NET MVC view with minor adjustment to the ids of the HTML elements.

Post a Comment

Previous Post Next Post