Skip to content

Usage

Array of constraints

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import Validation

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

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

Variadic list of constraints

 6
 7
 8
 9
10
// A variadic list of constraints
try validator.validate(
    password,
    against: NotBlankConstraint(), LengthConstraint(min: 6, max: 16)
)

Convenience API

 6
 7
 8
 9
10
// A convenience API for the existing constraints
try validator.validate(
    password,
    against: [.notBlank(), .length(min: 6, max: 16)]
)

Custom constraint

 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 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()]
)

Validation group

Default group

1
2
3
import Validation

let group = Group.default

Custom group

1
2
3
import Validation

let custom = Group(stringLiteral: "custom")
3
let custom: Group = "custom"
3
let custom = Group("custom")

Validation using groups

4
5
6
7
8
try validator.validate(
    password,
    against: NotBlankConstraint(), LengthConstraint(min: 6, max: 16)
    on: [custom]
)
4
5
6
7
8
try validator.validate(
    password,
    against: NotBlankConstraint(), LengthConstraint(min: 6, max: 16)
    on: [.default, custom]
)