There may be times where you need to restrict certain characters from being entered into fields at checkout. Perhaps you want to disallow special characters in the PO Number field, or only allow numerals to be entered into the phone number field. In this guide we will share a few examples of how that can be achieved via JavaScript.
Adding a custom JavaScript snippet
Using the steps below requires that you be familiar with how to add a JavaScript snippet to your site. We have a guide that details that here: https://support.commercebuild.com/article/how-to-add-a-javascript-snippet/
The following snippets can be used as guides that you can customize depending on your particular needs.
Only allow alpha numeric characters in the PO field at checkout
$(document).ajaxComplete(function( event, xhr, settings ) { var active_step = $('.active').attr('id'); if ( active_step == 'opc-review' ) { $('input#notes').on('input', function() { var enteredValue = $(this).val(); var cleanedValue = enteredValue.replace(/[^a-zA-Z0-9]/g, ''); $(this).val(cleanedValue); }); } });
Restrict the number of allowed characters in the comments field
$( document ).ajaxComplete(function( event, xhr, settings ) { var active_step = $('.active').attr('id'); if ( active_step == 'opc-review' ) { $("#comments").prop("maxLength", 254); } })
Prevent users from entering anything into the zip code field other than a number or a dash
if (window.location.href.indexOf("checkout") != -1) { $(document).on('blur', '#zip', function() { var selectedCountry = $('#country').val(); if (selectedCountry === 'USA') { var zipCode = $(this).val(); zipCode = zipCode.replace(/\//g, '-').replace(/\\/g, '-'); // Replace slashes with hyphen $(this).val(zipCode); } }); }