How to enforce phone number structure validation per country code in Memberstack Memberscript #41? Answered

Post author
Jordan Winn

Hey friends! Thank you so much for all of the support here so far. I am so grateful!

I build NursingUSA.com alongside Memberstack, and my client is wondering why phone numbers aren't validating to the proper structure presented from Memberscript #41 - Perfect Phone Number Inputs. I'd love for this script to force phone numbers to fit into the country code requirements.

Any thoughts on how to force validation? We are having people signup globally and some aren't including area codes, etc for their WhatsApp / Phone Number inputs.

In addition, I'm trying to figure out what to update in that script to display the same country code dropdown that was selected on signup (for the Edit Profile page).

Thank you in advance for the help!

Comments

4 comments

  • Comment author
    A J

    Hey Jordan Winn,

    I was testing out your use-case with some modifications in the approach shared by the memberscript you are using and seem to have setup a workable solution. I tested this out with a couple of numbers & couple of countries and it works as intended.

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"></script>
    <script>
      $(document).ready(function() {
        $('input[ms-code-phone-number]').each(function() {
          var input = this;
          var preferredCountries = $(input).attr('ms-code-phone-number').split(',');
    
          var iti = window.intlTelInput(input, {
            preferredCountries: preferredCountries,
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
          });
          
          var form = $(input).closest('form');
      
          setTimeout(function() {
              var $countryCodeInput = $('.country-code-field', form);
              var savedCountryCode = $countryCodeInput.val();          
              if (savedCountryCode) {              iti.setCountry(savedCountryCode); 
              }
          }, 500);
          
          input.addEventListener('change', formatPhoneNumber);
          input.addEventListener('keyup', formatPhoneNumber);
    
          function formatPhoneNumber() {
            var formattedNumber = iti.getNumber(intlTelInputUtils.numberFormat.NATIONAL);
            input.value = formattedNumber;
            if (iti.isValidNumber() || input.value.trim() === '') {
                hideValidationError();
            }
          }
          
          function showValidationError() {
                    $('.ph-error-msg', form).css('display', 'block');
          }
    
          function hideValidationError() {
                    $('.ph-error-msg', form).css('display', 'none');
          }
    
          form.find('input[type="submit"], button[type="submit"]').on('click', function(e) {
              var $countryCodeInput = $('.country-code-field', form);  
            var countryCodeToSave = iti.getSelectedCountryData().iso2;        
            $countryCodeInput.val(countryCodeToSave);
            var formattedNumber = iti.getNumber(intlTelInputUtils.numberFormat.INTERNATIONAL);
            input.value = formattedNumber;
            if (iti.isValidNumber()) {
              hideValidationError();
            } else {
              e.preventDefault();
              showValidationError();
              return false; 
            }
          });
        });
      });
    </script>
    
    1. Replace the memberscript you have applied with the above. You can create a clone of the profile page and test this out before implementing it on the actual page.
    2. Add a input field below the phone number field and give it a class name for example country-code-field and set its display property to none in the Webflow right side bar under styling tab.
      1. Create a custom field in Memberstack to save the country code that user selects
      2. Add the custom attribute to the field created in this step in the webflow form, as data-ms-member="CUSTOM-ID" with the relevant custom ID from the Memberstack' custom field.
    3. Add a text block to the form (probably below the phone number input field) with the text that you want to show as an error message when the user inputs an invalid formatted number.
      1. I set the text as 'Please enter a valid phone number.' for example.
      2. I set this text block's class as ph-error-msg and set its display property to none as well.

    Feel free to modify the validation code as per your use-case if you expect any specific format. The code that I shared with you checks if the number inputted is in the right format as per the country selected.

    In case, you change any of the class names, make sure you also edit the code accordingly. To work with the code as is, you can create the classes as shared in the steps.

    This should work for the profile forms (both after signup and in the edit profile page). Make sure to have this code on both the pages. The automatic country code selection (based on IP address) will not happen in this case, since you want to make sure the user selection is preserved.

    It will prevent form submission until a valid formatted number is given by the user and pre-fill the country selected in the profile form.

    Hope this helps. 

    0
  • Comment author
    Jordan Winn

    Thank you so much, @AJ! I added that code and it wasn't working, then realizes I'm using a modified version of the embed (I'm like 90% sure I pulled this from Memberscripts, but now I'm not sure!). Here's what I currently have in the

    :
    <!--International Phone Input Library-->
    <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/9.0.6/css/intlTelInput.css'>
    

    And here's what I currently have in the

    :
    <!--International phone input-->
    <script src='https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/9.0.6/js/intlTelInput.js'></script>
    
    <script>
      var input = $(".int-phone");
    
      input.intlTelInput({
        utilsScript:
          "https://cdn.jsdelivr.net/npm/intl-tel-input@18.1.1/build/js/utils.js",
        separateDialCode: true
      });
    
      input.on("change", function () {
        input.intlTelInput("setNumber", input.val()); //Format phone number e.g: "(123) 456-7890"
        var fullPhone = input.intlTelInput("getNumber"); //Get number typed by user
        $("#full_phone").val(fullPhone); //Add the full phone number with the dial code on a hidden input with "#full_phone" ID e.g.  +11234567890
      });
    </script>
    

    I'm not super code savvy, especially with js, so other than updating the 'input[ms-code-phone-number]' to ".int-phone", I'm sadly unsure what else needs to be adjusted. Any recommendations?
    Also I am happy to pay you for your time on this as well! Please let me know if we need to move this over to email.

    0
  • Comment author
    A J

    For testing purposes, can you clone the page you have the form setup with phone number and get rid of the custom code in the cloned page and paste the code that I shared in the Before </body> tag section of the custom code that you can find in the page settings.

    If possible, you can copy the form shared in this demo project for testing purposes so that you have a fresh form to test this specific use-case on.

    Can you try out the steps I mentioned in the cloned page and see if that works? If it does, then you can use the same approach to your actual page.

    In case, you face any blockers with the cloned page, you can share a read-only link of the site which will help me in troubleshooting.
    0
  • Comment author
    Jordan Winn

    Yes, will work on that next and do some additional testing to try to solve this! Thank you again so much, I may do some follow up on Monday as well. You are amazing!!

    0

Please sign in to leave a comment.