Fix: TextField Only Accepts Numbers in SwiftUI

Fix: TextField Only Accepts Numbers in SwiftUI

Written by

in

Quick answer: Use TextField with a value binding and formatter (iOS 13+) or format parameter (iOS 15+) to accept only numeric input. For String bindings, filter input with Combine’s onReceive. Both approaches reject non-numeric characters including pasted text.

Why this happens

SwiftUI’s basic TextField initializer takes a Binding<String> and imposes no validation. Users can type letters, paste arbitrary text, or use hardware keyboards that bypass the on-screen keyboard type. The keyboardType(.numberPad) modifier only affects the soft keyboard — it does not prevent paste or external keyboard input.

Apple introduced type-safe initializers that bind directly to numeric types. These initializers use a Formatter (iOS 13+) or the new FormatStyle API (iOS 15+) to parse and validate input, automatically rejecting anything that cannot be converted to the target number type.

How to fix it

1. Use format: with FormatStyle (iOS 15+)

This is the cleanest modern approach. Bind to an optional Double (or Int, Float) and pass .number format. The field stays empty until the user enters a valid number.

import SwiftUI

struct NumberFieldView: View {
    @State private var amount: Double?

    var body: some View {
        TextField("Amount", value: $amount, format: .number)
            .keyboardType(.decimalPad)
            .textFieldStyle(.roundedBorder)
            .padding()
    }
}

Key points:
– value: $amount binds to Double? — nil means empty field.
– format: .number uses the locale-aware NumberFormatStyle.
– Invalid keystrokes and pastes are ignored; the binding never updates.
– Add .keyboardType(.decimalPad) (or .numberPad for integers) for better UX.

2. Use formatter: with NumberFormatter (iOS 13+)

If you support iOS 13 or 14, use the formatter: initializer with a configured NumberFormatter.

import SwiftUI

struct LegacyNumberFieldView: View {
    @State private var quantity: Double?
    private let formatter: NumberFormatter = {
        let f = NumberFormatter()
        f.numberStyle = .decimal
        f.maximumFractionDigits = 0 // integer only
        return f
    }()

    var body: some View {
        TextField("Quantity", value: $quantity, formatter: formatter)
            .keyboardType(.numberPad)
            .textFieldStyle(.roundedBorder)
            .padding()
    }
}

Key points:
– Configure numberStyle (.decimal, .currency, .percent, etc.).
– Set maximumFractionDigits = 0 for integer-only input.
– Optional binding allows an empty field; non-optional forces a default value.

3. Filter a String binding with Combine (fallback)

When you must keep a Binding<String> (e.g., for existing validation logic), sanitize input in onReceive. This also handles paste and hardware keyboards.

import SwiftUI
import Combine

struct StringNumberFieldView: View {
    @State private var text = ""

    var body: some View {
        TextField("Numbers only", text: $text)
            .keyboardType(.numberPad)
            .onReceive(Just(text)) { newValue in
                let filtered = newValue.filter { "0123456789".contains($0) }
                if filtered != newValue {
                    text = filtered
                }
            }
            .textFieldStyle(.roundedBorder)
            .padding()
    }
}

How it works:
1. Just(text) emits the new string whenever @State changes.
2. onReceive filters out non-digits.
3. If the filtered string differs, we write it back, overwriting the invalid input.
4. import Combine is required for Just.

Tip: For decimal input, allow . once: "0123456789.".contains($0) && newValue.filter({$0 == "."}).count <= 1.

4. Dismiss the number pad with a toolbar

Number pads lack a Return key. Add a toolbar button to resign focus.

struct DismissibleNumberField: View {
    @State private var value: Double?
    @FocusState private var isFocused: Bool

    var body: some View {
        TextField("Value", value: $value, format: .number)
            .keyboardType(.decimalPad)
            .focused($isFocused)
            .toolbar {
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button("Done") { isFocused = false }
                }
            }
    }
}

How to prevent it

  • Prefer value:format: (iOS 15+) or value:formatter: (iOS 13+) over String binding + filtering.
  • Always set keyboardType to .numberPad, .decimalPad, or .numbersAndPunctuation for better UX.
  • Use optional numeric bindings (Double?) to allow an empty field.
  • Add a toolbar “Done” button when using number pads.
  • Test with paste, hardware keyboards, and iPad (which shows full keyboard even with .numberPad).

FAQ

Does keyboardType(.numberPad) alone prevent non-numeric input?

No. It only changes the soft keyboard. Users can still paste text, use hardware keyboards, or on iPad see the full keyboard. Always pair it with a validating initializer or Combine filtering.

Can I use Int instead of Double for whole numbers?

Yes. Change the binding to Int? and keep format: .number (or formatter.numberStyle = .none). The field will reject decimal points and non-integer input.

Why does my TextField show a default value instead of staying empty?

Non-optional bindings (@State var value: Double = 0) initialize with that default. Use @State var value: Double? so the field remains empty until the user enters a valid number.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.