Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Mar 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading