skip to content

In SwiftUI, how do you keep a sign-up Form's Create button disabled until the form is valid, and show inline validation messages?

level: middleimportance: must knowfreq 68%

answer

  1. derive, do not store, validity
  2. disabled flows down the tree
  3. outer disabled wins
  4. messages near the field
  5. block the double submit

basics

~20 s

Compute validity from the form's state in a computed property, apply .disabled(!isValid) to the Create button only, and show each message conditionally next to its control or in its Section footer, once the user has entered something.

solid answer

~40 s

Keep the inputs in `@State` (or a model) and derive validity with computed properties such as `emailLooksValid`, `isOldEnough` and `canCreate`, so they re-evaluate whenever the body does and can never go stale. Put `.disabled(!canCreate)` on the button, not on the whole form: `disabled(_:)` reaches everything beneath it through the `isEnabled` environment value, and Apple's documentation says an outer `disabled(true)` overrides an inner `disabled(false)`, so a disabled form also kills its Cancel button. Show messages with an `if` beside the control or in the `Section` footer, gated on the user having typed so a blank form is not covered in red. Fold an `isSubmitting` flag into `canCreate` to block double taps, and still validate on the server.

code

swift · 42 lines
swift
import SwiftUI

struct SignUpForm: View {
    @State private var email = ""
    @State private var birthday = Calendar.current.date(byAdding: .year, value: -18, to: .now) ?? .now
    @State private var acceptedTerms = false
    @State private var isSubmitting = false
    let submit: () async -> Void

    private var emailLooksValid: Bool { email.contains("@") && email.contains(".") }
    private var isOldEnough: Bool {
        Calendar.current.dateComponents([.year], from: birthday, to: .now).year ?? 0 >= 13
    }
    private var canCreate: Bool { emailLooksValid && isOldEnough && acceptedTerms && !isSubmitting }

    var body: some View {
        Form {
            Section {
                TextField("Email", text: $email)
                if !email.isEmpty && !emailLooksValid {
                    Text("Enter an email address like [email protected].")
                        .font(.footnote)
                        .foregroundStyle(.red)
                }
            }
            Section {
                DatePicker("Birthday", selection: $birthday, in: ...Date.now, displayedComponents: .date)
            } footer: {
                if !isOldEnough { Text("You must be 13 or older to sign up.") }
            }
            Toggle("I accept the terms", isOn: $acceptedTerms)
            Button("Create Account") {
                isSubmitting = true
                Task {
                    await submit()
                    isSubmitting = false
                }
            }
            .disabled(!canCreate)
        }
    }
}

go deeper

for a junior

Recall that disabled(_:) takes a Bool and that a computed property over the form's state is the simplest validity rule.

for a middle

Explain how disabled propagates through the isEnabled environment, why the outer value wins, and how footers and conditional views carry messages.

for a senior

Show that you scope disabling narrowly, block double submits, show errors only after interaction, and keep the server as the final authority.

for a principal

Discuss sharing validation rules between client and server so messages stay consistent as the sign-up requirements change.

## The shape of the problem A sign-up form collects an email address, a birthday and acceptance of the terms. The **Create** button should only work when all three are acceptable, and the user should see *why* it does not. In SwiftUI that means three things: a source of truth for the inputs, a rule that turns them into a verdict, and views that react to the verdict. ## Derive validity instead of storing it Hold the raw inputs in `@State` (or an observable model) and express every rule as a **computed property**: ```swift private var emailLooksValid: Bool { email.contains("@") && email.contains(".") } private var canCreate: Bool { emailLooksValid && isOldEnough && acceptedTerms && !isSubmitting } ``` Because `body` reads `canCreate`, and `canCreate` reads the state, SwiftUI re-evaluates it whenever any input changes. A separate `@State var isValid` updated from `onChange(of:)` handlers is the anti-pattern: miss one input and the button's state silently disagrees with the form. Keep rules in plain properties or in the model, where they are easy to unit-test. ## How disabled(_:) propagates `disabled(_:)` adds a condition that controls whether users can interact with a view, and it applies to the whole subtree beneath it. Two consequences matter: 1. **It is written into the environment.** The iOS 27 SDK's interface shows `disabled(_:)` as a transform of the environment value **`isEnabled`** (default `true`): the new value is the inherited one AND NOT the argument. Built-in controls read `isEnabled` and dim themselves; a custom row can read `@Environment(\.isEnabled)` and do the same. 2. **The outer `true` wins.** Because the transform can only turn `isEnabled` off, a child's `.disabled(false)` leaves an inherited `false` unchanged. Apple's documentation shows exactly this: a button with `.disabled(false)` inside an `HStack` with `.disabled(true)` stays non-interactive. You cannot re-enable a child of a disabled container. So apply `.disabled(!canCreate)` to the **Create button only**. Disabling the whole `Form` while a request is in flight would also disable its Cancel button and every field, with no way to carve out an exception. ## Showing messages where they help Inline feedback is just conditional views: - **Next to the field:** an `if` inside the section that shows a short `Text` in a footnote font and a red foreground style when the rule fails. - **In the section footer:** `Section { ... } footer: { if !isOldEnough { Text("You must be 13 or older to sign up.") } }` places help and errors under the group they describe. - **Gate on interaction:** a blank form should not open covered in errors. Show the email message only once the field is non-empty, or track whether the user has left the field. - **Say what to do,** not only what is wrong: "Enter an email address like [email protected]." Constrain controls up front where you can, so fewer messages are needed: a birthday `DatePicker` with `in: ...Date.now` and `displayedComponents: .date` cannot produce a future date at all. ## Submitting safely - **Block the double tap.** Set `isSubmitting = true` before the async call and include `!isSubmitting` in `canCreate`, so a second tap during the request does nothing. - **Re-enable on failure.** Reset the flag when the request finishes either way, and show the server's error inline. - **Keep server validation.** Client checks are for feedback; an email that passes a local pattern can still be taken or undeliverable, and only the server can say so. ## A checklist interviewers listen for | Concern | Weak answer | Strong answer | |---|---|---| | Where validity lives | `@State var isValid` updated by hand | computed from the inputs on every body pass | | What gets disabled | the whole `Form` | the Create button, plus fields only while required | | When errors show | immediately on an empty form | after the user has entered something | | Double submit | not considered | `isSubmitting` folded into the enable rule | | Final authority | the client | the server, with errors shown inline | ## Summary Treat validation as a pure function of the form's state, let `disabled(_:)` express its result on the one button that needs it, and remember that disabling a container disables everything inside it irreversibly. The rest — where messages appear and when — is ordinary conditional view code inside the form's sections.

  • A custom card row inside a disabled Section still looks tappable; how do you make it dim like the built-in controls?
    Read `@Environment(\.isEnabled) private var isEnabled` in the row and change its appearance, such as lowering opacity or switching to a secondary foreground style, when it is `false`. `disabled(_:)` sets that environment value for the whole subtree, so the row learns about the outer modifier without any extra parameter.
  • Why can't a Cancel button inside a disabled Form be re-enabled with .disabled(false)?
    Apple's documentation for `disabled(_:)` says higher views in the hierarchy can override the value set on a view, and its example shows an outer `disabled(true)` beating an inner `disabled(false)`. The fix is to disable narrower subtrees — the fields or the Create button — rather than the container that also holds Cancel.

  • Store isValid in its own @State and update it by hand
  • Disable the whole Form and re-enable Cancel inside it
  • Show every error message before the user types anything
  • Client-side validation makes server checks unnecessary
  • A child's .disabled(false) re-enables it inside a disabled container