How do I validate forms and show inline errors in SwiftUI?

In SwiftUI, validating forms and displaying inline errors can enhance user experience by providing real-time feedback. This process typically involves creating a form, binding user input to state variables, and checking these variables against validation rules. Below is an example demonstrating how to validate a form with inline error messages in SwiftUI.

struct ContentView: View { @State private var name: String = "" @State private var email: String = "" @State private var nameError: String? @State private var emailError: String? var body: some View { Form { Section(header: Text("User Information")) { TextField("Enter your name", text: $name) .onChange(of: name) { _ in validateName() } if let nameError = nameError { Text(nameError).foregroundColor(.red) } TextField("Enter your email", text: $email) .onChange(of: email) { _ in validateEmail() } if let emailError = emailError { Text(emailError).foregroundColor(.red) } } Button("Submit") { // Handle form submission validateName() validateEmail() if nameError == nil && emailError == nil { // Proceed with form submission } } } } private func validateName() { if name.isEmpty { nameError = "Name cannot be empty." } else { nameError = nil } } private func validateEmail() { if email.isEmpty { emailError = "Email cannot be empty." } else if !email.contains("@") { emailError = "Invalid email format." } else { emailError = nil } } }

SwiftUI Form Validation Inline Errors User Experience