Could Someone Give me Advice for Managing User Input in SwiftUI Forms?

Hello there, :wave:

I am working on a project in SwiftUI, and I am facing a challenge when it comes to managing user input in forms. I am developing a feature where users fill out multiple fields; and I need to validate the input before submitting the form.

Specifically; I am wondering about the best practices for handling dynamic form validation in SwiftUI.

I want to provide feedback as users type e.g., checking if an email address is valid or if a password meets requirements. I am considering using @State to track errors for each field; but I am unsure if this is the most efficient or cleanest approach. Would using something like @Binding or a custom validation model be better? :thinking:

Once all the fields are validated; I need to submit the form. Should I use a custom submit function; or is there a more SwiftUI-centric way to manage this? Also, how can I prevent the form from being submitted if any of the fields are invalid? :thinking:

Also, I have gone through this post; https://codecrew.codewithchris.com/t/andrews-journey-to-release-an-app-cybersecurity which definitely helped me out a lot.

I am also curious about how to dynamically update the UI based on validation. For example; if one field fails; I want to highlight it and show a message without disrupting the flow of the form.

Thank you for your help and assistance. :innocent:

@davidcook

Hi David,

Here is my take on validation (others may differ).

There is an .onChange(of: modifier that can monitor a variable associated with a TextField. As you type characters you can validate on the fly to identify illegal characters or invalid formatting and provide immediate feedback to the user via code you specify in the .onChange closure (it could be by calling a function that you define such as validateEmail()). The best way to provide that feedback is via a Text view that shows up in red underneath that associated TextField. You could make that error Text view hidden normally and when populated with an error statement then make it visible.

As far as preventing the user from submitting the form unless all fields are valid, you can have a function or computed variable called, say, isFornComplete that returns true if there are no errors in the form and false if there are.

Then, you use a modifier like .disabled(!isFormComplete()) on the submit button, which will prevent the user from submitting the form until there are no errors.

1 Like