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 as needed.
Only allow alpha numeric in PO field at checkout
<script> // Only allow alpha numeric in 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); }); } }); </script>
Restrict the number of allowed characters in the comments field
<script> $( document ).ajaxComplete(function( event, xhr, settings ) { var active_step = $('.active').attr('id'); if ( active_step == 'opc-review' ) { $("#comments").prop("maxLength", 254); } }) ;</script>
Prevent users from entering anything into the zip code field other than a number or a dash
<script> 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); } }); } </script>