I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
so it needs to be a string after running through the regex check? Also, I need a check before it hits the regex that checks if it’s in proper us phone number format.
Yes, it’s an invaluable aspect of communication let alone learning to program at any level, but unfortunately, people have lives and can’t answer promptly. I’ve figured out my issues and solved the project with guidance from GPT architecture. Using the guideline of not generating a single line of code and only revising the logistical approach and explaining methods (.trim, ? operator, .test, etc…). Here’s the finished project.
document.addEventListener('DOMContentLoaded', () => {
// setting elements to variables
const userInput = document.getElementById('user-input');
const checkButton = document.getElementById('check-btn');
const clearButton = document.getElementById('clear-btn');
const resultDisplay = document.getElementById('results-div');
checkButton.addEventListener('click', () => {
let input = userInput.value;
// Check if input is empty
if (input.trim() === '') {
window.alert('Please provide a phone number');
} else {
// Updated regex to match valid US phone numbers
const regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s.-]?\d{3}[\s.-]?\d{4}$/;
// Update the result display based on whether the input matches the regex
resultDisplay.textContent = regex.test(input)
? `Valid US number: ${input}`
: `Invalid US number: ${input}`;
}
});
// Clear button functionality
clearButton.addEventListener('click', () => {
userInput.value = '';
resultDisplay.textContent = '';
});
});
The issue was due to a lack of awareness of how in-depth and specific regex values can be. Thanks to GPT there was a logistical revision along with a realization there was no need to remove any whitespace or syntax outside of using .trim for whitespace at the beginning or end of the string. The regex should be formatted in such a manner that phone numbers in the provided example would pass through the regex.test().
1 555-555-5555
1 (555) 555-5555
1(555)555-5555
1 555 555 5555
5555555555
555-555-5555
(555)555-5555
Thank you for your time also, I do apologize for the lack of clarity on the situation.
Granted I will admittingly say AI does still have flaws and It makes it easier for me personally but can lead others to an issue of actually having to read and understand what it’s producing/approach it’s taking toward a solution. More frequently there are errors in generated/user logic or a lack of in-depth explanation provided by the user. It also seems to try to be more pleasing rather than corrective.