Hey I’m having an issue with my validation logic. My function is correctly identifying incorrect US numbers but incorrectly identifying the valid ones (reading them as invalid). I’ve tried adjusting whitespaces, making them optional and playing around with the hyphens. Am i missing an anchor or?
function validator() {
const inputValue = input.value.trim();
if (inputValue === "") {
alert("Please provide a phone number");
return;
}
const countryCode = /^(1|\+1)?\s*?/;
const areaCode = /^(\(\d{3}\))?\s*?\d{3}/;
const mainNumber = /\s*?-\?\s*?\d{3}-?\s*?\d{4}/;
const phoneRegex = new RegExp(`${countryCode.source}${areaCode.source}${mainNumber.source}`);
if (phoneRegex.test(inputValue)) {
results.textContent = `Valid US number: ${inputValue}`;
} else {
results.textContent = `Invalid US number: ${inputValue}`;
}
return;
}