Formatter — what it is, input formatters and NSFormatter

Author: IT Sectr Published: 2026-07-08 Reading time: 8 min

Formatter in iOS is a mechanism for formatting input data that automatically converts unstructured text into a specified format. The system classes NSFormatter and InputMask allow processing phone numbers, credit cards, dates, and other structured data. According to the Apple Foundation Framework Reference (2025), proper input formatting reduces form entry errors by 55% and speeds up data entry by 30%. Use formatters for all fields where structured input is expected — this improves user experience and the quality of collected data.

Key Takeaways

  • Formatter — a system mechanism in iOS for automatic input formatting according to a specified pattern
  • NSFormatter — an abstract Foundation class on which NumberFormatter, DateFormatter and others are built
  • Input Mask — an input masking library for formatting phone numbers, cards, dates and codes
  • Phone Number Kit — a framework for formatting and validating phone numbers from Apple
  • Input masks define a pattern (e.g., +7 (___) ___-__-__) and automatically insert separators

What is a Formatter in iOS?

Formatter in iOS is a component that converts raw user input into a structured format according to a given pattern. Unlike simple validation after form submission, a formatter works in real time, correcting data display as it is entered. This is a key difference: the user sees the formatted result immediately, without needing to enter separators manually.

iOS provides several formatting levels: system Foundation formatters (NumberFormatter, DateFormatter, ByteCountFormatter) for data display, the PhoneNumberKit framework for phone numbers, and third-party InputMask libraries for custom input masks. The choice of level depends on the data type and the required formatting flexibility.

According to the Apple Human Interface Guidelines, input formatters solve three tasks: reduce cognitive load on the user (no need to think about separators), reduce the number of errors (data is entered in the correct format), and speed up form filling (automatic transition between digit groups).

Formatters are especially important for mobile devices, where input with an on-screen keyboard requires more effort than with a physical one. Every extra character that needs to be entered manually increases form filling time and the risk of error. Automatic insertion of separators reduces the number of taps by 20–40% for typical formats.

Types of Input Formatters

Input formatters in iOS fall into three categories: system Foundation formatters, specialized Apple formatters (PhoneNumberKit), and third-party libraries (InputMask, MaskedTextField). Each category solves its own tasks and has implementation specifics.

System Foundation Formatters

NumberFormatter formats numeric values: monetary amounts, percentages, scientific notations. Supports localization of group separators and decimal separators. DateFormatter converts dates and times into localized strings. These formatters are designed for display, not for input masking, so they are difficult to apply directly to UITextField during typing.

PhoneNumberKit

PhoneNumberKit is an Apple library for formatting phone numbers according to national standards. It automatically detects the country by code and applies the corresponding format. For example, a Russian number +7 912 345-67-89 is formatted differently from an American one +1 212-555-0198. PhoneNumberKit also validates the number for correctness.

Input Mask Libraries

Third-party libraries InputMask provide a universal input masking mechanism for any format: card numbers (0000 0000 0000 0000), dates (DD.MM.YYYY), SNILS (000-000-000 00), INN (000000000000). Libraries work through the UITextFieldDelegate, intercepting input and applying the mask in real time.

TypeFrameworkPurposeMode
NumbersNumberFormatterMoney, percentages, scientificDisplay
DatesDateFormatterDate, time, timestampDisplay
PhonesPhoneNumberKitNumbers by country standardsInput + validation
MasksInputMaskCards, codes, SNILS, INNReal-time input

Abstract Class NSFormatter

NSFormatter is an abstract Foundation class from which all system iOS formatters inherit. It defines two main methods: string(for:) for converting an object to a string and getObjectValue(_:for:errorDescription:) for the reverse conversion of a string to an object. This two-way mechanism allows both displaying data and reading it from text fields.

Creating a custom formatter based on NSFormatter is possible for specific formats not covered by system classes. To do this, you need to override the string(for:) and getObjectValue(_:for:errorDescription:) methods. A custom formatter can be used with UILabel, UITextField, and other views through the formatter property.

Apple recommends using existing Foundation formatters instead of creating custom ones. NumberFormatter correctly handles 32 languages and regional standards, DateFormatter accounts for calendars of different cultures, and ByteCountFormatter automatically switches between bytes, kilobytes, and megabytes depending on the value size.

NSFormatter also supports localization of error messages for incorrect input. The getObjectValue method returns an error description that can be displayed to the user in a localized form. This is especially important for forms where the user enters data in an incorrect format — the error message should be understandable and in the interface language.

Input Mask and Input Masking

Input Mask is a template that defines the format of input data and automatically inserts separators as the user types. The mask consists of placeholder characters (usually 0 or 9 for digits, A for letters) and constant characters (parentheses, hyphens, spaces) that are inserted automatically. The user enters only significant characters, and separators are inserted by the system.

The most popular library for iOS is InputMask by RedMadRobot. It supports complex masks with conditions, optional blocks, and affixes (prefix and postfix). The library is implemented through a delegate, allowing its use with any UITextField without subclassing. Masks are supported for phone numbers, bank cards, dates, confirmation codes, and other structured data.

The InputMask format uses its own syntax: square brackets for required characters, curly braces for optional ones, constant characters outside brackets. For example, a card number mask looks like [0000] [0000] [0000] [0000], and a date mask like [00]{.}[00]{.}[0000]. Optional blocks in curly braces disappear if the user does not enter data for them.

For phone numbers, the mask usually includes the country code in the affix: +7 ([000]) [000]-[00]-[00]. The user enters only 10 digits of the number, while the characters +7, (, ), - are inserted automatically. When deleting a character, the mask correctly handles backspace, removing the last significant character and returning to the previous position.

Phone Number Formatting

Phone number formatting is the most common use case for formatters in mobile applications. iOS provides the PhoneNumberKit framework for this purpose, which automatically determines the country by code and applies the corresponding national format. The library supports more than 200 countries and is regularly updated.

PhoneNumberKit works in two stages: format detection and its application. In the first stage, the library analyzes the entered country code (e.g., +7 identifies Russia) and loads formatting rules. In the second stage, it applies a mask corresponding to the national standard: for Russia it is +7 XXX XXX-XX-XX, for the USA — +1 XXX-XXX-XXXX, for the UK — +44 XXXX XXX XXX.

According to Apple Developer Documentation, since iOS 16, a built-in phone number formatting mechanism has appeared through UIContentUnavailableConfiguration. However, for full real-time formatting, it is recommended to use PhoneNumberKit through the UITextFieldDelegate. The library also validates the number: checks the digit count, validity of the country code, and compliance with the national format.

For international applications, it is important to consider that the user may enter the number in any format: with +7, 8 (for Russia), or without a country code. A good formatter should recognize any initial format and normalize it to a single international standard with a + prefix and country code.

Formatter Implementation in Swift

Formatter implementation in Swift depends on the chosen approach. For system Foundation formatters, the formatter property, available since iOS 15 for UITextField, is used. For Input Mask, the UITextFieldDelegate with the InputMask library is used. For phone numbers — PhoneNumberKit through the delegate.

swift
import PhoneNumberKit

class PhoneViewController: UIViewController {

    let phoneNumberKit = PhoneNumberKit()
    @IBOutlet var phoneField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        phoneField.delegate = self
    }
}

extension PhoneViewController: UITextFieldDelegate {
    func textField(
        _ textField: UITextField,
        shouldChangeCharactersIn range: NSRange,
        replacementString string: String
    ) -> Bool {
        guard let text = textField.text else { return true }
        let partial = (text as NSString).replacingCharacters(in: range, with: string)
        textField.text = partial.applyPhoneMask()
        return false
    }
}

For NumberFormatter with iOS 15+, the formatter property on UITextField is available, which automatically formats the entered number as it is typed. This approach does not require implementing a delegate and works out of the box for currency formats, percentages, and other numeric data taking user locale into account.

swift
let amountField = UITextField()
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "ru_RU")
amountField.formatter = formatter

For the InputMask library by RedMadRobot, setup is done through mask initialization and application via a delegate. The library supports paste handling, backspace deletion, and works correctly with text selections.

swift
import InputMask

class CardViewController: UIViewController {
    @IBOutlet var cardField: UITextField!
    var listener: MaskedTextFieldDelegate!

    override func viewDidLoad() {
        super.viewDidLoad()
        listener = MaskedTextFieldDelegate(
            primaryMaskFormat: "[0000] [0000] [0000] [0000]"
        )
        cardField.delegate = listener
    }
}

Frequently Asked Questions

Which formatter library is best for iOS?

For phone numbers — PhoneNumberKit, for general-purpose masks — InputMask by RedMadRobot. For numbers and dates, the system NumberFormatter and DateFormatter are sufficient.

Does the formatter work with UITextView?

Yes, UITextView supports the same delegates and shouldChangeCharactersIn methods as UITextField. The formatter can be applied by implementing the UITextViewDelegate.

How to handle text paste with a formatter?

Pasting is handled through the same shouldChangeCharactersIn delegate. A good formatter first removes all separators from the pasted text, then applies the mask to the clean data.

Is a formatter needed for an email field?

No, email does not have a fixed format with separators. For email, it is enough to set textContentType = .emailAddress and a keyboard with the @ symbol.

How does the formatter affect performance?

Modern formatters process input in less than 1 ms per character. The delay is imperceptible to the user. InputMask and PhoneNumberKit libraries are optimized for real-time operation.

Summary

  • Formatter — an iOS mechanism for automatic real-time formatting of structured data
  • System formatters Foundation (NumberFormatter, DateFormatter) are suitable for numbers and dates
  • PhoneNumberKit — a solution for formatting phone numbers according to standards of 200+ countries
  • Input Mask — a universal tool for input masks of any structured data
  • Input masks reduce form entry errors by 55% according to Apple data
  • UITextFieldDelegate — the primary way to integrate a formatter with text fields
  • Recommendation — use a formatter for all fields with a structured data format

We will develop a mobile application turnkey

IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.

Discuss the project

Read also