@@ -60,8 +60,8 @@ struct PhoneNumberField: View {
6060 . foregroundColor ( foregroundColor)
6161 . focused ( $focusedField, equals: . callingCode)
6262 . onChange ( of: callingCode) { code in
63- if !phoneNumber . isEmpty {
64- text = " \( code) \( phoneNumber ) "
63+ if !numericPhoneNumber . isEmpty {
64+ text = " \( code) \( numericPhoneNumber ) "
6565 }
6666 }
6767
@@ -72,14 +72,22 @@ struct PhoneNumberField: View {
7272 SwiftUI . TextField ( placeholder, text: $phoneNumber)
7373 . disableAutocorrection ( true )
7474 . focused ( $focusedField, equals: . phoneNumber)
75- . onChange ( of: phoneNumber) { text in
76- if text. isEmpty {
75+ . onChange ( of: phoneNumber) { newValue in
76+ // Only allow characters used for representing phone numbers, i.e. numbers, spaces, parentheses and hyphens.
77+ let allowedCharacters = newValue. filter ( " 0123456789-() " . contains)
78+ guard phoneNumber == allowedCharacters else {
79+ phoneNumber = allowedCharacters
80+ return
81+ }
82+
83+ if numericPhoneNumber. isEmpty {
7784 // 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
7885 self . text = " "
7986 } else {
80- self . text = " \( callingCode) \( text ) "
87+ self . text = " \( callingCode) \( numericPhoneNumber ) "
8188 }
82- if validator. state != . normal || !text. isEmpty {
89+
90+ if validator. state != . normal || !phoneNumber. isEmpty {
8391 validator. validate ( )
8492 }
8593 }
@@ -108,9 +116,6 @@ struct PhoneNumberField: View {
108116 }
109117 }
110118 . focused ( $isFocused)
111- . onAppear {
112- validator. value = $phoneNumber
113- }
114119 . onChange ( of: isFocused) { isFocused in
115120 if isFocused && !Platform. isMacOS {
116121 focusedField = . phoneNumber
@@ -147,6 +152,10 @@ struct PhoneNumberField: View {
147152 case callingCode
148153 case phoneNumber
149154 }
155+
156+ private var numericPhoneNumber : String {
157+ return phoneNumber. filter ( " 0123456789 " . contains)
158+ }
150159}
151160
152161/// This allows the user to select a dialing code from a list of all available ones,
0 commit comments