The following code effectively limits a TextFild to only numbers, periods . and commas , which is what I want. The issue is that it allows the user to enter a period . and a comma , if a period is entered first.
How can I modify the Regex expression below to prevent the user from entering a comma , if a period . already exists, and vice-versa?
struct TextFieldNumbersOnly: View {
@State private var inputValue = ""
var body: some View {
TextField("enter numbers", text: self.$inputValue)
//.keyboardType(.decimalPad) //commented out for testing purposes only
.onReceive(Just(self.inputValue), perform: self.textInputValidator)
}
func textInputValidator(newValue: String) {
if newValue.range(of: "^[\\d]*(?:\\.?\\,?[\\d]*)?$", options: .regularExpression) != nil {
self.inputValue = newValue
} else if !self.inputValue.isEmpty {
self.inputValue = String(newValue.prefix(self.inputValue.count - 1))
}
}
}
FYI - If I type a comma before a period, it doesn't let me enter the period, which is what I want, it just doesn't do it the other way around.