Data Validation in Swift (iOS/macOS): Overview of Tools and Libraries
Data validation is one of the key aspects of developing high-quality mobile and desktop applications in Swift. It ensures that user input matches the expected format and business rules. In this article, we will cover the main approaches, built-in mechanisms, and popular libraries for validation in the Apple ecosystem.
Why is Validation Important?
Without validation, an application risks receiving incorrect data, which can lead to:
- Errors in server-side operations
- Unexpected client-side crashes
- Security vulnerabilities (SQL injection, XSS)
- Poor user experience
Built-in Capabilities of Swift and Foundation
Swift and the Foundation framework provide basic yet powerful tools for validation.
1. Validation with NSPredicate
NSPredicate is a powerful tool for filtering and validating data. It supports regular expressions, making it convenient for validating emails, phone numbers, and other strings.
import Foundation
func isValidEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,64}" let predicate = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return predicate.evaluate(with: email)}
// Example usagelet testEmail = "user@example.com"print(isValidEmail(testEmail)) // true2. Validation with NSRegularExpression
For more complex scenarios, NSRegularExpression is convenient to use.
func isValidPassword(_ password: String) -> Bool { // Minimum 8 characters, one uppercase, one lowercase, one digit let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)[a-zA-Z\\\\d]{8,}$" do { let regex = try NSRegularExpression(pattern: passwordRegex) let range = NSRange(location: 0, length: password.utf16.count) return regex.firstMatch(in: password, options: [], range: range) != nil } catch { return false }}
print(isValidPassword("Swift1234")) // trueprint(isValidPassword("swift123")) // false (no uppercase)Popular Libraries for Validation
While built-in tools are sufficient for simple tasks, specialized libraries are more convenient for complex forms with multiple rules.
1. Validator (by Adam Waite)
One of the most popular libraries for string validation in Swift. It supports chain validation and custom validators.
// Installation via SPM: .package(url: "https://github.com/adamwaite/Validator.git", from: "3.0.0")import Validator
let emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: "Invalid email")let nameRule = ValidationRuleLength(min: 2, max: 50, error: "Name must be between 2 and 50 characters")
let email = "test@mail.ru"let result = email.validate(rule: emailRule)switch result {case .valid: print("Email is valid")case .invalid(let errors): print(errors.first?.message ?? "Error")}2. SwiftValidators (by gkaimakas)
A lightweight library with a declarative syntax. Great for real-time field validation.
import SwiftValidators
let phone = "+7 (999) 123-45-67"if Validator.isPhoneNumber().trim().validate(phone) { print("Phone is valid")} else { print("Invalid format")}Validation in SwiftUI with Combine
Modern SwiftUI applications often use Combine for reactive validation. This allows errors to be displayed instantly as the user types.
import SwiftUIimport Combine
class RegistrationViewModel: ObservableObject { @Published var email = "" @P Also in library
Geolocation and Maps in JavaScript (Node.js): Libraries and Tools
ts-mockito for TypeScript: Complete Guide with Examples
Sarama for Go: Complete Guide with Examples
Reactive Programming in Swift: Combine and RxSwift for iOS/macOS
Creating CLI Tools in Node.js: Overview of Commander, Yargs, and Inquirer Frameworks