|
| 1 | +/* |
| 2 | + * Copyright 2025 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | + * in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the |
| 10 | + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 11 | + * express or implied. See the License for the specific language governing permissions and |
| 12 | + * limitations under the License. |
| 13 | + */ |
| 14 | + |
| 15 | +package com.firebase.ui.auth.compose.configuration.validators |
| 16 | + |
| 17 | +import com.firebase.ui.auth.compose.configuration.string_provider.AuthUIStringProvider |
| 18 | +import com.firebase.ui.auth.compose.data.CountryData |
| 19 | +import com.google.i18n.phonenumbers.NumberParseException |
| 20 | +import com.google.i18n.phonenumbers.PhoneNumberUtil |
| 21 | + |
| 22 | +internal class PhoneNumberValidator( |
| 23 | + override val stringProvider: AuthUIStringProvider, |
| 24 | + val selectedCountry: CountryData, |
| 25 | +) : |
| 26 | + FieldValidator { |
| 27 | + private var _validationStatus = FieldValidationStatus(hasError = false, errorMessage = null) |
| 28 | + private val phoneNumberUtil = PhoneNumberUtil.getInstance() |
| 29 | + |
| 30 | + override val hasError: Boolean |
| 31 | + get() = _validationStatus.hasError |
| 32 | + |
| 33 | + override val errorMessage: String |
| 34 | + get() = _validationStatus.errorMessage ?: "" |
| 35 | + |
| 36 | + override fun validate(value: String): Boolean { |
| 37 | + if (value.isEmpty()) { |
| 38 | + _validationStatus = FieldValidationStatus( |
| 39 | + hasError = true, |
| 40 | + errorMessage = stringProvider.missingPhoneNumber |
| 41 | + ) |
| 42 | + return false |
| 43 | + } |
| 44 | + |
| 45 | + try { |
| 46 | + val phoneNumber = phoneNumberUtil.parse(value, selectedCountry.countryCode) |
| 47 | + val isValid = phoneNumberUtil.isValidNumber(phoneNumber) |
| 48 | + |
| 49 | + if (!isValid) { |
| 50 | + _validationStatus = FieldValidationStatus( |
| 51 | + hasError = true, |
| 52 | + errorMessage = stringProvider.invalidPhoneNumber |
| 53 | + ) |
| 54 | + return false |
| 55 | + } |
| 56 | + } catch (_: NumberParseException) { |
| 57 | + _validationStatus = FieldValidationStatus( |
| 58 | + hasError = true, |
| 59 | + errorMessage = stringProvider.invalidPhoneNumber |
| 60 | + ) |
| 61 | + return false |
| 62 | + } |
| 63 | + |
| 64 | + _validationStatus = FieldValidationStatus(hasError = false, errorMessage = null) |
| 65 | + return true |
| 66 | + } |
| 67 | +} |
0 commit comments