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!
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