Skip to content

Commit 62da46a

Browse files
committed
add validation
1 parent d686607 commit 62da46a

File tree

1 file changed

+27
-3
lines changed
  • packages/boxel-ui/addon/src/components/phone-input

1 file changed

+27
-3
lines changed

Diff for: packages/boxel-ui/addon/src/components/phone-input/index.gts

+27-3
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@ import {
99
type CountryCode,
1010
getExampleNumber,
1111
type CountryCallingCode,
12+
isValidPhoneNumber,
1213
} from 'libphonenumber-js';
1314
// @ts-expect-error import not found
1415
import examples from 'libphonenumber-js/mobile/examples';
1516
import { countries, type TCountryCode, getEmojiFlag } from 'countries-list';
16-
import { TemplateOnlyComponent } from '@ember/component/template-only';
17+
import type { TemplateOnlyComponent } from '@ember/component/template-only';
18+
import { debounce } from 'lodash';
1719

1820
interface Signature {
1921
Args: {};
@@ -58,9 +60,19 @@ const getCountryInfo = (countryCode: CountryCode): CountryInfo | undefined => {
5860
export class PhoneInput extends Component<Signature> {
5961
@tracked items: Array<CountryInfo> = [];
6062
@tracked selectedItem: CountryInfo = getCountryInfo('US')!;
63+
@tracked validationState: InputValidationState = 'initial';
64+
@tracked input: string = '';
6165

6266
@action onSelectItem(item: CountryInfo): void {
6367
this.selectedItem = item;
68+
if (this.input.length > 0) {
69+
this.validationState = isValidPhoneNumber(
70+
this.input,
71+
this.selectedItem.code,
72+
)
73+
? 'valid'
74+
: 'invalid';
75+
}
6476
}
6577

6678
constructor(owner: unknown, args: any) {
@@ -79,14 +91,26 @@ export class PhoneInput extends Component<Signature> {
7991
return undefined;
8092
}
8193

82-
get validationState(): InputValidationState {
83-
return this.placeholder ? 'valid' : 'invalid';
94+
get phoneNumber(): string {
95+
return `+${this.selectedItem.callingCode} `;
96+
}
97+
98+
@action onInput(v: string): void {
99+
this.debouncedInput(v);
84100
}
85101

102+
private debouncedInput = debounce((input: string) => {
103+
this.validationState = isValidPhoneNumber(input, this.selectedItem.code)
104+
? 'valid'
105+
: 'invalid';
106+
this.input = input;
107+
}, 300);
108+
86109
<template>
87110
<BoxelInputGroup
88111
@placeholder={{this.placeholder}}
89112
@state={{this.validationState}}
113+
@onInput={{this.onInput}}
90114
>
91115
<:before as |Accessories|>
92116
<Accessories.Select

0 commit comments

Comments
 (0)