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…


This content originally appeared on DEV Community and was authored by Alhiane Lahcen

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")
]

🛠️ 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"] ?? [])")
}

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"] ?? [])")
}

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)")
}

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"] ?? [])")
}

🖼️ 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)
                }
            }
        }
    }
}

🧪 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)
    }
}

🎉 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! 🚀


This content originally appeared on DEV Community and was authored by Alhiane Lahcen


Print Share Comment Cite Upload Translate Updates
APA

Alhiane Lahcen | Sciencx (2024-09-25T12:56:01+00:00) ValidatorKit: Simplify iOS Data Validation with Swift. Retrieved from https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/

MLA
" » ValidatorKit: Simplify iOS Data Validation with Swift." Alhiane Lahcen | Sciencx - Wednesday September 25, 2024, https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/
HARVARD
Alhiane Lahcen | Sciencx Wednesday September 25, 2024 » ValidatorKit: Simplify iOS Data Validation with Swift., viewed ,<https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/>
VANCOUVER
Alhiane Lahcen | Sciencx - » ValidatorKit: Simplify iOS Data Validation with Swift. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/
CHICAGO
" » ValidatorKit: Simplify iOS Data Validation with Swift." Alhiane Lahcen | Sciencx - Accessed . https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/
IEEE
" » ValidatorKit: Simplify iOS Data Validation with Swift." Alhiane Lahcen | Sciencx [Online]. Available: https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/. [Accessed: ]
rf:citation
» ValidatorKit: Simplify iOS Data Validation with Swift | Alhiane Lahcen | Sciencx | https://www.scien.cx/2024/09/25/validatorkit-simplify-ios-data-validation-with-swift/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.