Skip to content

Commit c7ae724

Browse files
Add phone format
1 parent 96cf9d7 commit c7ae724

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
## Format Phone Number
2+
3+
```html
4+
<div class="phoneNumberInput-Container">
5+
<input class="phoneNumber" type="text" />
6+
<span class="errorMessage">Invalid Phone number format</span>
7+
</div>
8+
```
9+
10+
```css
11+
.errorMessage {
12+
display: none;
13+
color: red;
14+
}
15+
16+
.errorMessage .show {
17+
display: block;
18+
}
19+
```
20+
21+
```js
22+
const phoneField = document.querySelector(".phoneNumber");
23+
24+
function formatPhone(event) {
25+
const phoneInput = event.target.value;
26+
const validPhoneFormat = /(\(\d{3}\)?)-\d{3}-\d{4}/;
27+
28+
if (phoneInput.length < 10) {
29+
const errorSpan = document.querySelector(".errorMessage");
30+
errorSpan.innerHTML = "Phone Number too short. Enter in this format: (###)-###-####";
31+
32+
errorSpan.classList.add('show');
33+
return;
34+
}
35+
36+
const isPhoneFormatted = validPhoneFormat.test(phoneInput);
37+
38+
if (!isPhoneFormatted) {
39+
const phoneAreaCode = phoneInput.slice(0, 3);
40+
const phoneFirstThree = phoneInput.slice(3, 6);
41+
const phoneLastFour = phoneInput.slice(6, 10);
42+
43+
event.target.value = `(${phoneAreaCode})-${phoneFirstThree}-${phoneLastFour}`;
44+
}
45+
}
46+
47+
phoneField.addEventListener("change", formatPhone);
48+
phoneField.addEventListener("keyUp", formatPhone);
49+
50+
// debounce can be added if event listener is added on input, to limit number of calls to format the phone
51+
```

0 commit comments

Comments
 (0)