Validation component

Swift MIT License Actions Status Codacy Badge Contributing Twitter

Installation

Swift

Download and install Swift

Swift Package

mkdir MyApp
cd MyApp
swift package init --type executable // Creates an executable app named "MyApp"

Package.swift

// swift-tools-version:5.3

import PackageDescription

let package = Package(
    name: "MyApp",
    dependencies: [
        .package(name: "chaqmoq-validation", url: "https://github.com/chaqmoq/validation.git", .branch("master"))
    ],
    targets: [
        .target(name: "MyApp", dependencies: [
            .product(name: "Validation", package: "chaqmoq-validation"),
        ]),
        .testTarget(name: "MyAppTests", dependencies: [
            .target(name: "MyApp")
        ])
    ]
)

Build

swift build -c release

Usage

main.swift

import Validation

let password = "12345"
let validator = Validator()

// An array of constraints
try validator.validate(
    password,
    against: [NotBlankConstraint(), LengthConstraint(min: 6, max: 16)]
)
// A variadic list of constraints
try validator.validate(
    password,
    against: NotBlankConstraint(), LengthConstraint(min: 6, max: 16)
)
// A convenience API for the existing constraints
try validator.validate(password, against: [.notBlank(), .length(min: 6, max: 16)])

// A custom validator
struct CustomValidator: ConstraintValidator {
    func validate(_ value: String, against constraints: [Constraint]) throws {
        // A validation logic here.
    }
}

// A custom constraint
struct CustomConstraint: Constraint {
    let validator: ConstraintValidator = CustomValidator()
}

// An array of constraints
try validator.validate(
    password,
    against: [NotBlankConstraint(), LengthConstraint(min: 6, max: 16), CustomConstraint()]
)
// A variadic list of constraints
try validator.validate(
    password,
    against: NotBlankConstraint(), LengthConstraint(min: 6, max: 16), CustomConstraint()
)

Run

swift run

Tests

swift test --enable-test-discovery --sanitize=thread