github vapor/vapor 4.32.0
Array validation

latest releases: 4.99.3, 4.99.2, 4.99.1...
3 years ago
This patch was authored and released by @tanner0101.

Adds support for validating nested arrays (#2473, #2238, fixes #2158).

Assuming the following User definition:

struct User: Codable {
    struct Hobby: Codable {
        var title: String
    }

    var hobbies: [Hobby]
}

Validations for User and its nested array of hobbies can be defined like so:

extension User: Validatable {
    static func validations(_ validations: inout Validations) {
        validations.add(each: "hobbies") { i, hobby in
            hobby.add("title", as: String.self, is: .characterSet(.alphanumerics + .whitespaces))
        }
    }
}

Note that the closure receives the items index i. This can be used to dynamically adjust validations depending on index:

validations.add(each: "hobbies") { i, hobby in
    // Don't validate first item.
    if i != 0 {
        hobby.add("title", as: String.self, is: .characterSet(.alphanumerics + .whitespaces))
    }
}

Also note how this method complements Validations.add(_:) (without the each parameter) for validating nested dictionaries:

struct User: Codable, Validatable {
    struct Hobby: Codable {
        var title: String
    }

    var hobby: Hobby

    static func validations(_ validations: inout Validations) {
        validations.add("hobbies") { hobby in
            hobby.add("title", as: String.self, is: .characterSet(.alphanumerics + .whitespaces))
        }
    }
}

Don't miss a new vapor release

NewReleases is sending notifications on new releases.