Data Validation in Swift: Validator Library

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Validator and why is it needed?

Validator is a lightweight library for data validation in Swift, designed for iOS and macOS applications. It allows you to declaratively describe rules for checking user input, avoiding cumbersome if-else constructions. The main goal is to simplify the processing of forms, API requests, and any other data that requires validation for correctness (email, password, age, number range, etc.).

Installation

Validator is installed via Swift Package Manager (SPM). Add the dependency to Package.swift:

.package(url: "https://github.com/adamwaite/Validator.git", from: "3.2.0")

Or via Xcode: File → Add Packages → paste the repository URL.

Main Features

  • String validation: email, URL, regular expressions, length, non-empty.
  • Numeric validation: range, minimum/maximum value, integers.
  • Composite rules: combining multiple conditions via And / Or.
  • Custom validators: creating your own rules using closures.
  • Integration with UIKit/SwiftUI: ready-made extensions for UITextField and SwiftUI View.

Swift Code Example (iOS)

import Validator

// 1. Define a rule for emaillet emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: "Invalid email")

// 2. Validate the stringlet email = "test@example.com"let result = email.validate(rule: emailRule)

switch result {case .valid: print("Email is valid")case .invalid(let errors): print("Errors: \\(errors)")}

// 3. Composite rule: password from 8 to 20 characters, contains at least one digitlet passwordRule = ValidationRuleLength(min: 8, max: 20, error: "Password length from 8 to 20") && ValidationRulePattern(pattern: ".*[0-9].*", error: "Password must contain a digit")

let password = "SecurePass1"let passwordResult = password.validate(rule: passwordRule)

// 4. Validation of UITextField (UIKit)let textField = UITextField()textField.text = "user@domain.com"textField.validate(rule: emailRule) { result in // handle the result}

When to use Validator

  • Registration/authorization forms (email, password, phone).
  • Input validation in UITextField / SwiftUI TextField.
  • Data validation before sending to the server.
  • Filtering and checking user content (reviews, comments).
  • Parsing and validation of JSON/API responses.

The library is ideal for projects that require a flexible, readable, and extensible data validation system without unnecessary boilerplate code.

Recommendations