|
1 | 1 | import { Component, OnInit } from '@angular/core'; |
2 | 2 | import { |
3 | 3 | UntypedFormBuilder, |
| 4 | + UntypedFormControl, |
4 | 5 | UntypedFormGroup, |
5 | 6 | Validators, |
6 | 7 | } from '@angular/forms'; |
@@ -50,16 +51,38 @@ export class TwoFactorAuthComponent implements OnInit { |
50 | 51 | async ngOnInit() { |
51 | 52 | this.loading = true; |
52 | 53 | this.methods = await this.api.idpuser.getTwoFactorMethods(); |
| 54 | + |
53 | 55 | this.loading = false; |
54 | 56 | } |
55 | 57 |
|
56 | 58 | formatPhoneNumber(value: string) { |
57 | 59 | let numbers = value.replace(/\D/g, ''); |
58 | | - let char = { 0: '(', 3: ') ', 6: ' - ' }; |
59 | | - let formatted = ''; |
| 60 | + let countryCode = ''; |
| 61 | + |
| 62 | + if (numbers.startsWith('00')) { |
| 63 | + const match = numbers.match(/^00(\d{1,3})/); |
| 64 | + if (match) { |
| 65 | + countryCode = `+${match[1]}`; |
| 66 | + numbers = numbers.substring(match[0].length); |
| 67 | + } |
| 68 | + } else if (numbers.startsWith('1') && value.startsWith('+')) { |
| 69 | + countryCode = '+1'; |
| 70 | + numbers = numbers.substring(1); |
| 71 | + } else if (value.startsWith('+')) { |
| 72 | + const match = numbers.match(/^(\d{1,3})/); |
| 73 | + if (match) { |
| 74 | + countryCode = `+${match[1]}`; |
| 75 | + numbers = numbers.substring(match[1].length); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + const char = { 0: '(', 3: ') ', 6: '-' }; |
| 80 | + let formatted = countryCode ? `${countryCode} ` : ''; |
60 | 81 | for (let i = 0; i < numbers.length; i++) { |
61 | 82 | formatted += (char[i] || '') + numbers[i]; |
62 | 83 | } |
| 84 | + |
| 85 | + // Update the form control without emitting events |
63 | 86 | this.form.get('contactInfo').setValue(formatted, { emitEvent: false }); |
64 | 87 | } |
65 | 88 |
|
@@ -119,13 +142,22 @@ export class TwoFactorAuthComponent implements OnInit { |
119 | 142 | } else if (this.method === 'sms') { |
120 | 143 | contactInfoControl.setValidators([ |
121 | 144 | Validators.required, |
122 | | - Validators.maxLength(17), |
123 | | - Validators.minLength(17), |
| 145 | + this.smsLengthValidator(), |
124 | 146 | ]); |
125 | 147 | } |
126 | 148 | contactInfoControl.updateValueAndValidity(); |
127 | 149 | } |
128 | 150 |
|
| 151 | + private smsLengthValidator() { |
| 152 | + return (control: UntypedFormControl) => { |
| 153 | + const value = control.value || ''; |
| 154 | + if (value.length === 14 || value.length === 18 || value.length === 17) { |
| 155 | + return null; |
| 156 | + } |
| 157 | + return { invalidSmsLength: true }; |
| 158 | + }; |
| 159 | + } |
| 160 | + |
129 | 161 | hasMethod(method: string): boolean { |
130 | 162 | return this.methods.some((m) => m.method === method); |
131 | 163 | } |
|
0 commit comments