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.
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)
}
}
}
The full series is available on my profile and the components can also be found at shipios.app/components.
Happy Coding!
Top comments (0)