DEV Community

Cover image for ValidatorKit: Simplify iOS Data Validation with Swift
Alhiane Lahcen
Alhiane Lahcen

Posted on

ValidatorKit: Simplify iOS Data Validation with Swift

ValidatorKit: Simplify iOS Form Validation with Swift

Are you tired of writing repetitive, error-prone form validation code for your iOS apps? Meet ValidatorKit, a lightweight and flexible Swift package designed to streamline form validation in iOS development. Whether you're working with SwiftUI or UIKit, ValidatorKit offers a fluent API that makes defining and applying validation rules a breeze.

๐Ÿš€ Key Features

  • Easy-to-use fluent API
  • Support for both SwiftUI and UIKit
  • Customizable validation rules
  • Lightweight with no external dependencies

๐Ÿ“ฆ Installation

Add ValidatorKit to your project using Swift Package Manager:

dependencies: [
    .package(url: "https://github.com/Alhiane/ValidatorKit.git", from: "1.0.0")
]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ› ๏ธ Usage Examples

Basic Validation: Single Field, Single Rule

import ValidatorKit

let schema = ValidationSchema()
    .field("email").required()
    .ready() // Always call .ready() to finalize the schema

let input = ["email": "user@example.com"]
let result = schema.validate(input)

if result.isValid {
    print("Email is valid!")
} else {
    print("Validation failed: \(result.errors["email"] ?? [])")
}
Enter fullscreen mode Exit fullscreen mode

Multiple Rules for a Single Field

let schema = ValidationSchema()
    .field("password")
        .required()
        .min(8)
        .pattern("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$")
    .ready()

let input = ["password": "pass123"]
let result = schema.validate(input)

if !result.isValid {
    print("Password errors: \(result.errors["password"] ?? [])")
}
Enter fullscreen mode Exit fullscreen mode

Multiple Fields with Multiple Rules

let schema = ValidationSchema()
    .field("username").required().min(3)
    .field("email").required().email()
    .field("age").required().min(18)
    .ready()

let input = [
    "username": "jo",
    "email": "not-an-email",
    "age": 16
]

let result = schema.validate(input)

for (field, errors) in result.errors {
    print("\(field) errors: \(errors)")
}
Enter fullscreen mode Exit fullscreen mode

Custom Validation Rules

let schema = ValidationSchema()
    .field("password").required().custom(message: "Password must be at least 8 characters") { value in
        guard let password = value as? String, password.count >= 8 else {
            return false
        }
        return true
    }
    .ready()

let input = ["password": "123abc4567"]
let result = schema.validate(input)

if !result.isValid {
    print("Password errors: \(result.errors["password"] ?? [])")
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ–ผ๏ธ SwiftUI Integration

Here's how you can use ValidatorKit in a SwiftUI form:

import SwiftUI
import ValidatorKit

struct RegistrationForm: View {
    @State private var username = ""
    @State private var email = ""
    @State private var password = ""
    @State private var validationErrors: [String: [String]] = [:]

    let schema = ValidationSchema()
        .field("username").required().min(3)
        .field("email").required().email()
        .field("password").required().min(8)
        .ready()

    var body: some View {
        Form {
            TextField("Username", text: $username)
            TextField("Email", text: $email)
            SecureField("Password", text: $password)

            Button("Register") {
                let result = schema.validate([
                    "username": username,
                    "email": email,
                    "password": password
                ])
                validationErrors = result.errors
                if result.isValid {
                    // Proceed with registration
                }
            }

            ForEach(validationErrors.keys.sorted(), id: \.self) { field in
                if let errors = validationErrors[field] {
                    Text(errors.joined(separator: ", "))
                        .foregroundColor(.red)
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Testing Your Validation Logic

ValidatorKit makes it easy to test your validation schemas:

import XCTest
@testable import ValidatorKit

class ValidatorKitTests: XCTestCase {
    func testRegistrationFormValidation() {
        let schema = ValidationSchema()
            .field("username").required().min(3)
            .field("email").required().email()
            .field("password").required().min(8)
            .ready()

        // Test valid input
        let validInput = ["username": "john", "email": "john@example.com", "password": "password123"]
        let validResult = schema.validate(validInput)
        XCTAssertTrue(validResult.isValid)

        // Test invalid input
        let invalidInput = ["username": "jo", "email": "not-an-email", "password": "short"]
        let invalidResult = schema.validate(invalidInput)
        XCTAssertFalse(invalidResult.isValid)
        XCTAssertEqual(invalidResult.errors.count, 3)
    }
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰ Conclusion

ValidatorKit offers a powerful, flexible, and easy-to-use solution for form validation in iOS applications. By providing a fluent API, support for custom rules, and seamless integration with both UIKit and SwiftUI, ValidatorKit simplifies one of the most common and often tedious aspects of iOS development.

Whether you're building a simple login form or a complex multi-step registration process, ValidatorKit can help you ensure data integrity and improve user experience with minimal effort. Its lightweight design and lack of external dependencies make it an excellent choice for projects of all sizes.

๐Ÿ“š Learn More

To dive deeper into ValidatorKit and explore its full potential, check out the GitHub repository.

For more iOS development insights and tutorials, visit my personal website at https://alhiane.com.

Happy coding! ๐Ÿš€

Top comments (0)