DEV Community

Cover image for Forms and Input Handling in iOS 18 - #30DaysOfSwift
Vaibhav Dwivedi
Vaibhav Dwivedi

Posted on

Forms and Input Handling in iOS 18 - #30DaysOfSwift

Day 24: Designing Forms and Handling User Input Validation πŸ“‹

Let's go to the basics today with by creating forms and handling user input in SwiftUI.

Forms are a core part of many apps for collecting data from users.

Image description

Let’s jump in!


Code

SwiftUI provides the Form container, making it easy to create user-friendly input forms.

import SwiftUI

struct UserFormView: View {
    @State private var username = ""
    @State private var email = ""
    @State private var password = ""
    @State private var errorMessage = ""

    var body: some View {
        Form {
            // Username Input
            Section(header: Text("Username")) {
                TextField("Enter your username", text: $username)
                    .autocapitalization(.none)
                    .disableAutocorrection(true)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }

            // Email Input
            Section(header: Text("Email")) {
                TextField("Enter your email", text: $email)
                    .autocapitalization(.none)
                    .keyboardType(.emailAddress)
                    .disableAutocorrection(true)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }

            // Password Input
            Section(header: Text("Password")) {
                SecureField("Enter your password", text: $password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }

            // Error Message
            if !errorMessage.isEmpty {
                Text(errorMessage)
                    .foregroundColor(.red)
            }

            // Submit Button
            Button(action: {
                validateForm()
            }) {
                Text("Submit")
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
        }
        .navigationTitle("User Form")
    }

    // Step 3: Validate the form inputs
    func validateForm() {
        if username.isEmpty || email.isEmpty || password.isEmpty {
            errorMessage = "All fields are required!"
        } else if !email.contains("@") {
            errorMessage = "Invalid email address!"
        } else if password.count < 6 {
            errorMessage = "Password must be at least 6 characters!"
        } else {
            errorMessage = ""
            // Handle successful form submission (e.g., save data)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The full series is available on my profile and the components can also be found at shipios.app/components.

Happy Coding!

Postmark Image

20% off for developers who'd rather build features than debug email

Stop wrestling with email delivery and get back to the code you love. Postmark handles the complexities of email infrastructure so you can ship your product faster.

Start free

Top comments (0)

Postmark Image

"Please fix this..."

Focus on creating stellar experiences without email headaches. Postmark's reliable API and detailed analytics make your transactional emails as polished as your product.

Start free

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay