Question

Force the removal of a space between numbers in a phone field.

  • 31 May 2023
  • 2 replies
  • 45 views

Badge

Hey all,

Is there anyway to force the removal of a space in a form field?

For example, we are collecting UK phone numbers in a form then sending them via a web-hook to our lead distribution software. Some leads enter their number with a space which fails on the delivery end.

We can accept this: 07000123123

We cannot accept this: 07000 123123

Any ideas?


2 replies

Userlevel 4
Badge

Hey @brandy_rogers,

 

Thanks for your post in the Unbounce Community 👋

 

Whilst I don’t have anything for you which forcibly removes any spaces added in the phone number field, there is a way you can prevent spaces being added by visitors to your pages with a little bit of Javascript.

 

The following page has a bunch of different custom form validation options:
 

One of which is a ‘digits only’ option:

https://gist.github.com/johnnyopao/5158c3530f0098838aa0

The error message could then be customised to ask the visitor to remove all spaces from the phone number field.

 

I hope this helps!

Userlevel 3
Badge +1

Hey @brandy_rogers 

Try this:

// Assuming you have an input field with the id "phone"
var inputField = document.getElementById("phone");

inputField.addEventListener("input", function() {
  var phoneNumber = inputField.value.replace(/\s/g, ""); // Remove all spaces
  inputField.value = formatPhoneNumber(phoneNumber);
});

function formatPhoneNumber(phoneNumber) {
  var formattedNumber = phoneNumber;

  if (phoneNumber.length === 10) {
    formattedNumber = phoneNumber.replace(/(\d{4})(\d{3})(\d{3})/, "$1-$2-$3");
  }

  return formattedNumber;
}

 

This code snippet combines the event listener for input changes and the formatting logic into a single script. It removes spaces from the input field value using `replace(/\s/g, "")`, and then formats the phone number with hyphens if it has a length of 10 digits using a regular expression and the `replace()` function.

Make sure to replace `"phone"` with the actual id of your input field in the code. You can add this code to your HTML file within a `<script>` tag or include it in your JavaScript file.

If you need a hand, you can visit us at: www.happyagencies.com 

Reply