-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
50 lines (38 loc) · 1.18 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* Valid formats for US phone numbers
*/
const userInput = document.getElementById('user-input');
const checkButton = document.getElementById('check-btn');
const clearButton = document.getElementById('clear-btn');
const resultsDiv = document.getElementById('results-div');
const validRegex = [
// 1 555-555-5555
/^1 \d{3}-\d{3}-\d{4}$/,
// 1 (555)555-5555
/^1 \(\d{3}\)\d{3}-\d{4}$/,
// 1(555)555-5555
/^1\(\d{3}\)\d{3}-\d{4}$/,
// 1 555 555 5555
/^1 \d{3} \d{3} \d{4}$/,
// 5555555555
/^\d{10}$/,
// 555-555-5555
/^\d{3}-\d{3}-\d{4}$/,
// (555)555-5555
/^\(\d{3}\)\d{3}-\d{4}$/,
// 1 (555) 555-5555
/^1 \(\d{3}\) \d{3}-\d{4}$/,
];
const isValidFormat = (str) => validRegex.some((regex) => regex.test(str));
checkButton.addEventListener('click', () => {
if (userInput.value === '') {
alert('Please provide a phone number');
return;
}
resultsDiv.textContent = isValidFormat(userInput.value)
? `Valid US number: ${userInput.value}`
: `Invalid US number: ${userInput.value}`;
userInput.value = '';
});
clearButton.addEventListener('click', () => {
resultsDiv.textContent = '';
});