SwiftUI validate input in textfields

Reason for recursion:

Updating the value in the didSet is not a problem when it is not coupled to TextField.

In your example, when the text in Textfield changes, it updates the textValidator.text. Inside didSet if you update textValidator.text, it will update the text in TextField

Textfield => textValidator.text => Textfield => textValidator.text ... recursively

In the AudioChannel example there is no direct coupling and so there is no problem.

Approach:

  • TextField needs a binding don't directly provide the binding to a variable.
  • You need a way to replace the unwanted text before updating the variable.
  • You can create a Binding by providing get and set closures.

Code:

import SwiftUI

class Model : ObservableObject {
    
    @Published var text : String = "" {
        didSet {
            print("text = \(text)")
        }
    }
}


struct ContentView: View {
    
    @ObservedObject var model : Model
    
    var body: some View {
        TextField("testing", text: Binding(get: {self.model.text},
                                           set: {self.model.text = $0.replacingOccurrences(of: "\\W", with: "", options:.regularExpression) }))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(model: Model())
    }
}