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!

Top comments (0)