You can try something like this. I tried this for Credit card validation. You can play around with your own validation in the set method.
@State private var value = ""
TextField("Enter your text", text: Binding(
get: { value },
set: { newVal in
if value.removeSpaces.count < 16 {
if newVal.removeSpaces.elementsEqual(value.removeSpaces) &&
newVal.removeSpaces.count.isMultiple(of: 4) {
value = newVal + " "
} else {
value = newVal
}
}
}))
And, I have written a small extension to string that removes the spaces.
extension String {
var removeSpaces: String {
replacingOccurrences(of: " ", with: "")
}
}
Not sure, if this exactly fits your purpose. But, you can always playground with setter based on the condition you want, taking mine as reference. Cheers!!!