Data Validation in Swift (iOS/macOS): Libraries, Tools, and Practical Examples
Data validation is one of the key aspects of developing high-quality iOS and macOS applications. Without reliable input validation, users may encounter errors, incorrect interface behavior, or even crashes. In this article, we will explore the best libraries and approaches for data validation in Swift, along with specific code examples.
Why is Data Validation Needed?
Validation allows you to:
- Guarantee the correctness of input data (email, phone number, password).
- Prevent errors on the server side.
- Improve user experience through instant feedback.
- Enhance application security.
Popular Libraries for Validation in Swift
Today, there are several proven libraries that simplify data validation:
- Validated — a lightweight library with support for Combine and SwiftUI.
- SwiftValidator — one of the first libraries for validating text fields.
- Validator (by Adamwaite) — a simple and flexible tool with many built-in rules.
- Regex — not a library, but a built-in mechanism for working with regular expressions, often used for validation.
Example 1: Email Validation Using Regular Expression
The simplest way is to use NSRegularExpression or the built-in range(of:options:) method.
import Foundation
func isValidEmail(_ email: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,64}" let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex) return emailPredicate.evaluate(with: email)}
// Usageprint(isValidEmail("test@example.com")) // trueprint(isValidEmail("invalid-email")) // falseExample 2: Password Validation (Length, Digits, and Special Characters)
Often, a password must contain at least 8 characters, at least one digit, and one special character.
func isValidPassword(_ password: String) -> Bool { // Minimum 8 characters guard password.count >= 8 else { return false } // Check for a digit let digitRegex = ".*[0-9]+.*" let digitPredicate = NSPredicate(format: "SELF MATCHES %@", digitRegex) guard digitPredicate.evaluate(with: password) else { return false } // Check for a special character let specialCharRegex = ".*[!@#$%^&*()_+\\\\-=\\\\[\\\\]{};':\\"\\\\\\\\|,./<>?]+.*" let specialPredicate = NSPredicate(format: "SELF MATCHES %@", specialCharRegex) guard specialPredicate.evaluate(with: password) else { return false } return true}
print(isValidPassword("Pass123!")) // trueprint(isValidPassword("weak")) // falseExample 3: Using the Validator Library (Adamwaite)
The Validator library provides a convenient syntax for chaining rules.
import Validator
let emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: "Invalid email")let emailResult = "user@domain.com".validate(rule: emailRule)
switch emailResult {case .valid: print("Email is valid")case .invalid(let errors): print("Error: \\(errors.first?.message ?? "")")}Example 4: Custom Validator for Age Verification
Sometimes you need to check that the user is above a certain age.
struct AgeValidator { static func isValid(age: Int) -> Bool { return age >= 18 && age <= 120 }}
// Usagelet userAge = 25if AgeValidator.isValid(age: userAge) { print( Also in library
Elasticsearch client for Rust: overview of the elasticsearch-rs library
Working with XML in Swift: Parsing, Creating, and Processing Data (iOS/macOS)
gRPC in Rust: Tonic and Grpc-rs Libraries with Examples
Testing in Kotlin: Frameworks and Tools for Quality Code
Working with ZIP Archives in Go (Golang): Creating, Reading, and Extracting Files