Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
1.1 kB
4
Indexable
Never
function validateItalianPhoneNumber(phoneNumber) {
    // Remove any non-digit characters from the phone number
    const cleanedPhoneNumber = phoneNumber.replace(/\D/g, '');

    // Check if the number starts with "+39" and transform it to "0039"
    if (cleanedPhoneNumber.startsWith('39')) {
        return '0039' + cleanedPhoneNumber.slice(2); // Return the corrected number
    }

    // Check if the number starts with "0039"
    if (!cleanedPhoneNumber.startsWith('0039')) {
        // If not, add "0039" to the beginning
        return '0039' + cleanedPhoneNumber; // Return the corrected number
    }

    // Return the original number if it already conforms to the correct format
    return cleanedPhoneNumber;
}

function validateAndCorrectPhoneNumber(phoneNumber) {
    const cleanedPhoneNumber = validateItalianPhoneNumber(phoneNumber);

    // Check if the cleaned number contains non-digits or has an incorrect number of digits
    if (!/^\d{10}$/.test(cleanedPhoneNumber)) {
        throw new Error('Invalid Italian phone number');
    }

    return cleanedPhoneNumber;
}
Leave a Comment