Data Validation in Swift (iOS/macOS): Best Practices and Tools

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

Data Validation in Swift (iOS/macOS): How to Choose the Right Tool



Data validation is one of the key stages in developing mobile and desktop applications in Swift. Without it, you cannot guarantee the correctness of user input, data security, or stable application performance. In this article, we will explore popular libraries and approaches to validation in the Apple ecosystem, and provide code examples for iOS and macOS.



Why is Data Validation Needed in Swift?

Users can enter anything: from an empty string to an SQL injection. Validation helps to:

  • prevent incorrect data (email without @, password shorter than 8 characters);
  • protect the application from attacks (XSS, injections);
  • improve UX — instantly highlight errors;
  • comply with business rules (e.g., age > 18).


Popular Libraries for Validation in Swift

While Foundation provides basic tools (NSPredicate, regular expressions), specialized libraries are better for complex scenarios.



1. Validator (by eMKa)

One of the most popular open-source libraries. Supports validation of strings, numbers, dates, and custom rules.

// Installation via SPM: https://github.com/eMKa/Validatorimport Validator

let emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard)let result = "test@example.com".validate(rule: emailRule)switch result {case .valid: print("Email is valid")case .invalid(let errors): print("Error: \\(errors.first?.message ?? "Unknown error")")}

The library supports rule chaining: "password123".validate(rules: [lengthRule, uppercaseRule, digitRule]). Perfect for registration forms.



2. SwiftValidator (by jpotts18)

A lightweight library for input field validation. Works with UIKit and SwiftUI. Allows you to set rules for each text field.

// Installation: https://github.com/jpotts18/SwiftValidatorimport SwiftValidator

let validator = Validator()validator.registerField(emailTextField, rules: [RequiredRule(), EmailRule()])validator.registerField(passwordTextField, rules: [RequiredRule(), MinLengthRule(length: 8)])

validator.validate { errors in if errors.isEmpty { print("All fields are valid") } else { for (field, error) in errors { print("Error in \\(field): \\(error.errorMessage)") } }}

Great for forms with many fields — you can manage validation centrally.



3. Regex (Built-in Foundation Solution)

If you don't want to add third-party dependencies, use NSRegularExpression. Suitable for simple checks.

func isValidEmail(_ email: String) -> Bool {    let pattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,64}"    let regex = try? NSRegularExpression(pattern: pattern)    let range = NSRange(location: 0, length: email.utf16.count)    return regex?.firstMatch(in: email, range: range) != nil}

// Usageif isValidEmail("user@example.com") { print("Email is valid")} else { print("Invalid email format")}

The downside is that it's hard to maintain and extend. For large projects, it's better to use libraries.



4. ValidatedPropertyKit (by the Community)

A modern approach using property wrappers. Allows you to annotate model properties directly.

// Installation: https://github.com/SvenTiigi/ValidatedPropertyKitimport ValidatedPropertyKit

struct User { @Validated(.nonEmpty, .email) var email: String @Validated(.minLength(8), .containsUppercase) var password: String}

var user = User()user.email = "test" // Error: invalid emailuser.password = "weak" // Error: password too shortprint(us

Recommendations