Created
August 7, 2024 17:31
-
-
Save HubSpotHanevold/d9a2f7bc19622f6d0c7295021e2b3f94 to your computer and use it in GitHub Desktop.
Phone number formatting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.main = async (event, callback) => { | |
var phone = event.inputFields['phone']; | |
console.log("Input Phone: ", phone) | |
const outputFields = { | |
valid: false, | |
validation_message: "", | |
phone: "" | |
} | |
validatePhone(phone,outputFields); | |
callback({ | |
outputFields: outputFields | |
}) | |
}; | |
function validatePhone(phone, outputFields){ | |
// Regular expression to match US numbers with or without hyphens, with optional country code | |
const regexWithCountryCode = /^\+1-?\d{3}-?\d{3}-?\d{4}$/; | |
const regexWithoutCountryCode = /^(\d{3}-?\d{3}-?\d{4})$/; | |
if (phone == null) { | |
outputFields.valid = false; | |
outputFields.validation_message = "Phone number is null"; | |
outputFields.phone = ""; | |
} else if (regexWithCountryCode.test(phone)) { | |
// The number is in the correct format with the country code | |
outputFields.valid = true; | |
outputFields.phone = phone.replace(/-/g, ''); // Normalize by removing hyphens | |
} else if (regexWithoutCountryCode.test(phone)) { | |
// The number matches the US format but lacks the country code | |
const normalizedNumber = phone.replace(/-/g, ''); // Remove hyphens for normalization | |
outputFields.valid = true; | |
outputFields.phone = `+1${normalizedNumber}`; // Prefix with the US country code | |
} else { | |
// Attempt to correct by stripping non-numeric characters and checking length | |
const digitsOnly = phone.replace(/\D/g, ''); | |
if (digitsOnly.length === 10) { | |
// Valid US number without country code | |
outputFields.valid = true; | |
outputFields.phone = `+1${digitsOnly}`; | |
} else if (digitsOnly.length === 11 && digitsOnly.startsWith('1')) { | |
// Includes country code but possibly entered with extra characters | |
outputFields.valid = true; | |
outputFields.phone = `+${digitsOnly}`; | |
} else { | |
// Cannot be corrected to a valid format | |
outputFields.valid = false; | |
outputFields.validation_error = 'Cannot correct the number to a valid US phone format'; | |
} | |
} | |
} | |
// Author: Alex Carpenter, Feb 2024 | |
// https://github.com/carpcarp/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment