Skip to content

Commit

Permalink
fix: Auto-filled phone numbers contain characters rejected by Cognito (
Browse files Browse the repository at this point in the history
…#56)

* fix: Auto-filled phone numbers contain characters rejected by Cognito

* Fixing required validation
  • Loading branch information
sebaland authored Mar 11, 2024
1 parent 3d6a757 commit 36d96ea
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions Sources/Authenticator/Views/Primitives/PhoneNumberField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ struct PhoneNumberField: View {
.foregroundColor(foregroundColor)
.focused($focusedField, equals: .callingCode)
.onChange(of: callingCode) { code in
if !phoneNumber.isEmpty {
text = "\(code)\(phoneNumber)"
if !numericPhoneNumber.isEmpty {
text = "\(code)\(numericPhoneNumber)"
}
}

Expand All @@ -72,14 +72,22 @@ struct PhoneNumberField: View {
SwiftUI.TextField(placeholder, text: $phoneNumber)
.disableAutocorrection(true)
.focused($focusedField, equals: .phoneNumber)
.onChange(of: phoneNumber) { text in
if text.isEmpty {
.onChange(of: phoneNumber) { newValue in
// Only allow characters used for representing phone numbers, i.e. numbers, spaces, parentheses and hyphens.
let allowedCharacters = newValue.filter("0123456789-() ".contains)
guard phoneNumber == allowedCharacters else {
phoneNumber = allowedCharacters
return
}

if numericPhoneNumber.isEmpty {
// If the phone number is empty, we consider this to be an empty input regardless of the calling code, as that one is automatically populated
self.text = ""
} else {
self.text = "\(callingCode)\(text)"
self.text = "\(callingCode)\(numericPhoneNumber)"
}
if validator.state != .normal || !text.isEmpty {

if validator.state != .normal || !phoneNumber.isEmpty {
validator.validate()
}
}
Expand Down Expand Up @@ -108,9 +116,6 @@ struct PhoneNumberField: View {
}
}
.focused($isFocused)
.onAppear {
validator.value = $phoneNumber
}
.onChange(of: isFocused) { isFocused in
if isFocused && !Platform.isMacOS {
focusedField = .phoneNumber
Expand Down Expand Up @@ -147,6 +152,10 @@ struct PhoneNumberField: View {
case callingCode
case phoneNumber
}

private var numericPhoneNumber: String {
return phoneNumber.filter("0123456789".contains)
}
}

/// This allows the user to select a dialing code from a list of all available ones,
Expand Down

0 comments on commit 36d96ea

Please sign in to comment.