How to create a swiftui textfield that allows the user to only input numbers and a single dot? In other words, it checks digit by digit as the user inputs, if the input is a
This is a simple solution for TextField validation: (updated)
struct ContentView: View {
@State private var text = ""
func validate() -> Binding {
let acceptableNumbers: String = "0987654321."
return Binding(
get: {
return self.text
}) {
if CharacterSet(charactersIn: acceptableNumbers).isSuperset(of: CharacterSet(charactersIn: $0)) {
print("Valid String")
self.text = $0
} else {
print("Invalid String")
self.text = $0
self.text = ""
}
}
}
var body: some View {
VStack {
Spacer()
TextField("Text", text: validate())
.padding(24)
Spacer()
}
}
}