• Resolved lberlin

    (@lberlin)


    Can we automatically format a postal code provided, e.g. XXXXXX, to add space between and limit the number of characters to 6?

Viewing 2 replies - 1 through 2 (of 2 total)
  • 0wordpress0user0

    (@0wordpress0user0)

    Example.

    if (preg_match(‘/^[A-Z]\d[A-Z]\s\d[A-Z]\d$/’, $postalCode)) { // Valid postal code } else { // Invalid postal code }

    Thread Starter lberlin

    (@lberlin)

    Thanks! I ended up using JavaScript instead. Here is the code:

    <script>
        document.addEventListener('DOMContentLoaded', function() {
        var postalCodeField = document.getElementById('ID');
        
        postalCodeField.addEventListener('input', function(event) {
            var currentValue = event.target.value;
            
            // Remove any existing spaces
            var cleanedValue = currentValue.replace(/\s/g, '');
            
            // Add space after third character
            if (cleanedValue.length > 3) {
                cleanedValue = cleanedValue.slice(0, 3) + ' ' + cleanedValue.slice(3);
            }
            
            event.target.value = cleanedValue;
        });
    });
    
    </script>
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Automatically format a postal code to the Canadian format’ is closed to new replies.