Hey so I finished writing my JS for the Telephone Validator project.
Something weird happens and I can’t work out what’s going on…
So for a few of the numbers the validation function returns true, but then I run it again and it returns false, then true and back and forth. Here’s the JS code, can I get a hint?
const
input = document.getElementById('user-input'),
checkButton = document.getElementById('check-btn'),
clearButton = document.getElementById('clear-btn'),
results = document.getElementById('results-div'),
testRegex = /(^1?)((\(\d{3}\))|(\d{3}))(\d{7}$)/g;
clearButton.addEventListener('click', () => {
results.textContent = '';
})
checkButton.addEventListener('click', () => {
if (!input.value) {
alert('Please provide a phone number.')
} else {
console.log("input value = ", input.value, typeof input.value);
validate(input.value);
input.value = '';
}
})
const validate = (str) => {
const cleanedStr = str.replace(/[ -]/g, '');
console.log('cleanedStr = ', cleanedStr, typeof cleanedStr);
if (testRegex.test(cleanedStr)) {
console.log('is valid number = ', true);
results.innerHTML += `<p>Valid US number: ${input.value}</p>`
} else {
console.log('is valid number = ', false);
results.innerHTML = `<p>Invalid US number: ${input.value}</p>`
}
};