Phone number formatting

Following on from Flexible/International Phone Formatting Options I discovered Cleave.js Telephone No. Formatting which showed me how to format the NZ mobile phone numbers the way I like.

2 Likes

Thanks for this Dean. It’s really useful.

Craig

Here is a solution Claude AI generated for the various telephone numbers here in NZ e.g. landline, mobile, 0800 or 1800 numbers

Javascript code:

‘’'LazyLoad.js([
https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js’,
https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/addons/cleave-phone.nz.js
], function () {
console.log(‘Cleave.js loaded!’);
initializeAllPhoneFields();
});

function initializeAllPhoneFields() {
function determinePhoneFormat(value) {
// Remove all non-digit characters for checking
const digitsOnly = value.replace(/\D/g, ‘’);

    // 0800 or 0502 numbers (10 digits)
    if ((digitsOnly.startsWith('0800') || digitsOnly.startsWith('0502')) && digitsOnly.length === 10) {
        return {
            blocks: [4, 3, 3],
            delimiters: [' ', ' ']
        };
    }
    
    // Mobile numbers (020, 021, 022, 025, 027)
    const mobilePrefix = ['020', '021', '022', '025', '027'];
    if (mobilePrefix.some(prefix => digitsOnly.startsWith(prefix))) {
        if (digitsOnly.length >= 7 && digitsOnly.length <= 11) {
            return {
                blocks: [3, 3, 5],
                delimiters: [' ', ' ']
            };
        }
    }
    
    // Standard 9-digit phone numbers
    if (digitsOnly.length === 9) {
        return {
            blocks: [2, 3, 4],
            delimiters: [' ', ' ']
        };
    }

    // Default format for other cases
    return {
        blocks: [3, 3, 4],
        delimiters: [' ', ' ']
    };
}

function initializeField(element) {
    let cleaveInstance;

    function updateFormat() {
        const value = element.value;
        const format = determinePhoneFormat(value);
        
        // Destroy existing instance if it exists
        if (cleaveInstance) {
            cleaveInstance.destroy();
        }

        // Create new instance with determined format
        cleaveInstance = new Cleave(element, {
            blocks: format.blocks,
            delimiters: format.delimiters,
            numericOnly: true
        });
    }

    // Initialize with current value
    updateFormat();

    // Update format when value changes
    element.addEventListener('input', updateFormat);
    
    // Store the cleave instance on the element for potential cleanup
    element.cleaveInstance = cleaveInstance;
}

function initializeAllFields() {
    // Find all phone input fields using the Knack class
    const phoneInputs = document.querySelectorAll('.kn-input-phone input');
    
    phoneInputs.forEach((element) => {
        // Check if this element already has a Cleave instance
        if (element.cleaveInstance) {
            element.cleaveInstance.destroy();
        }
        initializeField(element);
    });
    
    console.log(`Initialized ${phoneInputs.length} phone fields`);
}

// Initial initialization
initializeAllFields();

}

// Reinitialize on scene render for dynamic content
$(document).on(‘knack-scene-render.any’, function(event, scene) {
console.log(‘Scene render triggered’);
setTimeout(initializeAllPhoneFields, 100);
});
‘’’

1 Like