History
Loading...
Loading...
August 30, 2025
didSet property observers with @State to trigger validation instantly as users type. Combine this with computed properties to show real-time feedback without blocking input.This approach uses computed properties for validation logic and a separate state flag to control when validation feedback appears. The validation runs on every change but only displays feedback after the user starts interacting with the field.
struct ValidatedTextField: View {
@State private var email = ""
@State private var hasStartedEditing = false
private var isValidEmail: Bool {
email.contains("@") && email.contains(".")
}
private var showValidation: Bool {
hasStartedEditing && !email.isEmpty
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
TextField("Email", text: $email)
.textFieldStyle(.roundedBorder)
.onTapGesture {
hasStartedEditing = true
}
if showValidation {
HStack {
Image(systemName: isValidEmail ? "checkmark.circle.fill" : "xmark.circle.fill")
.foregroundColor(isValidEmail ? .green : .red)
Text(isValidEmail ? "Valid email" : "Please enter a valid email")
.font(.caption)
.foregroundColor(isValidEmail ? .green : .red)
}
.animation(.easeInOut(duration: 0.2), value: isValidEmail)
}
}
}
}Computed properties automatically update when their dependencies change, providing real-time feedback without manual state management. The `hasStartedEditing` flag prevents premature validation messages, creating a better user experience by not showing errors before users have a chance to input valid data.