Skip to content

Instantly share code, notes, and snippets.

@HubSpotHanevold
Created August 28, 2024 16:30
Show Gist options
  • Save HubSpotHanevold/56a5ab14656628bdb759ea12c994a864 to your computer and use it in GitHub Desktop.
Save HubSpotHanevold/56a5ab14656628bdb759ea12c994a864 to your computer and use it in GitHub Desktop.
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