How to restrict UITextField to take only numbers in Swift?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Restricting a UITextField to numeric input requires more than setting a numeric keyboard. Users can still paste text, use hardware keyboards, or enter locale-specific separators. A robust implementation combines keyboard hints, delegate validation, and final parsing rules.
Configure Keyboard for Better UX
Start with a keyboard type that matches expected input.
This improves user experience but does not guarantee valid input.
Enforce Input in Delegate Method
Use textField should change characters in range replacement string to validate candidate text.
Attach this delegate to your text field in viewDidLoad.
Support Decimal Input Safely
If decimals are allowed, handle locale-aware separators.
Do not hardcode period as decimal separator for all users.
Validate Final Value on Submit
Editing validation helps typing flow, but final form submission should parse and validate business constraints.
For decimal money values, parse with NumberFormatter and convert to a minor unit type if your backend expects cents.
Handle Paste and External Input Paths
Delegate validation covers typed and pasted input when applied correctly. Still, test these flows explicitly:
- copy and paste long invalid strings
- hardware keyboard entry in simulator
- VoiceOver focus and editing behavior
Numeric restrictions that work only with on-screen keyboard are incomplete.
Reusable Component Pattern
If many screens need numeric fields, centralize logic with a subclass.
This reduces repeated validation code and improves consistency.
Add Focused Input Tests
UI tests should cover typing, pasting, and deleting characters at different cursor positions. These scenarios catch edge cases where delegate logic looks correct but fails for replacement ranges in real user editing patterns.
Common Pitfalls
- Relying only on keyboard type for validation.
- Ignoring paste and hardware keyboard input.
- Hardcoding decimal separator and breaking locale behavior.
- Validating only on submit with poor user feedback.
- Duplicating validation logic across many controllers.
Summary
- Use numeric keyboard as guidance, not as full validation.
- Enforce numeric rules in delegate callbacks.
- Add locale-aware handling for decimal inputs.
- Re-validate and parse values at submission time.
- Centralize reusable input logic for consistency and maintainability.

