Contents

mohsinbmwm3/formkit

FormKit is a lightweight and flexible SwiftUI form framework designed for declarative, real-time, and user-friendly form validation. It supports per-field validation, error display, touched state tracking, and reactive form validity with a focus on SwiftUI best practices.

πŸš€ Features

  • βœ… Field-level validation (required, min length, custom rules)
  • βœ… Live validation on user interaction
  • βœ… Reactive form.isValid for controlling submit buttons
  • βœ… Clean separation of concerns using FormModel and FormField
  • βœ… Touched-based error visibility (errors show only after interaction)
  • βœ… Full SwiftUI compatibility (iOS 15+)
  • βœ… Demo app with Login and Registration flows

🧠 How It Works

1. Define a Form

@StateObject private var form = FormModel {
    ("email", FormField(value: "", validators: [
        .required(message: "Email is required"),
        .custom { $0.contains("@") ? nil : "Invalid email" }
    ]))
}

2. Bind and Validate

TextField("Email", text: form.binding(for: "email"))
    .onChange(of: form.binding(for: "email").wrappedValue) {
        form.validate(field: "email")
    }

if let error = form.error(for: "email"), form.touched(for: "email") {
    Text(error).foregroundColor(.red)
}

3. Check Overall Validity

Button("Submit") {
    form.markAllTouched()
}
.disabled(!form.isValid)

πŸ“± Demo App

The demo includes:

  • βœ‰οΈ Login form: email + password validation
  • πŸ“ Registration form: name, age, optional bio
  • πŸ—­ Navigation between login and registration
  • 🎨 Custom border styling without UIKit TextFieldStyle

Start with:

HomeView()

To navigate between both forms.


🧹 Validator Types

.required(message: String)
.minLength(Int, message: String)
.custom((Value) -> String?)  // nil means valid

More validators like .emailFormat, .matchesField, .numericOnly, etc. can be added easily.


πŸ§ͺ Future Plans

  • [ ] Async validation support
  • [ ] Reusable ValidatedTextField SwiftUI view
  • [ ] Form reset / initial values
  • [ ] Validation groups and conditional rules
  • [ ] Swift Package release

πŸ“‚ Folder Structure

FormKit/
β”œβ”€ Sources/
β”‚  β”œβ”€ FormModel.swift
β”‚  β”œβ”€ FormField.swift
β”‚  β”œβ”€ Validator.swift
β”‚  β”œβ”€ Protocols.swift
β”‚  └─ FormBuilder.swift
β”œβ”€ Demo/
β”‚  β”œβ”€ HomeView.swift
β”‚  β”œβ”€ LoginView.swift
β”‚  β”œβ”€ RegistrationView.swift
β”‚  └─ SharedUI.swift (validatedField)

πŸ“¦ Requirements

  • iOS 15+
  • Swift 5.7+
  • Xcode 14+

πŸ‘₯ Contributing

Found a bug or want to help extend validation? Open a PR or create an issue. Feedback is welcome!


πŸ“„ License

MIT License. Use it, fork it, ship it πŸš€

Package Metadata

Repository: mohsinbmwm3/formkit

Default branch: main

README: README.md