Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: validate each not taking required parameter into account #2859

Merged
merged 1 commit into from Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 19 additions & 11 deletions Sources/Vapor/Validation/Validation.swift
Expand Up @@ -52,18 +52,26 @@ public struct Validation {
self.init { container in
let result: ValidatorResult
do {
var results: [[ValidatorResult]] = []
var array = try container.nestedUnkeyedContainer(forKey: key)
var i = 0
while !array.isAtEnd {
defer { i += 1 }
var validations = Validations()
factory(i, &validations)
let nested = try array.nestedContainer(keyedBy: ValidationKey.self)
let result = validations.validate(nested)
results.append(result.results)
if container.contains(key), !required, try container.decodeNil(forKey: key) {
result = ValidatorResults.Skipped()
} else if container.contains(key) {
var results: [[ValidatorResult]] = []
var array = try container.nestedUnkeyedContainer(forKey: key)
var i = 0
while !array.isAtEnd {
defer { i += 1 }
var validations = Validations()
factory(i, &validations)
let nested = try array.nestedContainer(keyedBy: ValidationKey.self)
let result = validations.validate(nested)
results.append(result.results)
}
result = ValidatorResults.NestedEach(results: results)
} else if required {
result = ValidatorResults.Missing()
} else {
result = ValidatorResults.Skipped()
}
result = ValidatorResults.NestedEach(results: results)
} catch {
result = ValidatorResults.Codable(error: error)
}
Expand Down
59 changes: 59 additions & 0 deletions Tests/VaporTests/ValidationTests.swift
Expand Up @@ -233,13 +233,21 @@ class ValidationTests: XCTestCase {
var name: String
var age: Int
var hobbies: [Hobby]
var allergies: [Allergy]?

struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}

struct Allergy: Codable {
var title: String
init(title: String) {
self.title = title
}
}

static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
Expand All @@ -248,6 +256,9 @@ class ValidationTests: XCTestCase {
hobby.add("title", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
}
v.add("hobbies", as: [Hobby].self, is: !.empty)
v.add(each: "allergies", required: false) { i, allergy in
allergy.add("title", as: String.self, is: .characterSet(.letters))
}
}
}

Expand All @@ -268,6 +279,54 @@ class ValidationTests: XCTestCase {
XCTAssertThrowsError(try User.validate(json: invalidNestedArray)) { error in
XCTAssertEqual("\(error)", "hobbies at index 0 title contains '€' (allowed: whitespace, A-Z, a-z, 0-9) and at index 1 title is less than minimum of 5 character(s)")
}

let invalidNestedArray2 = """
{
"name": "Tanner",
"age": 24,
"allergies": [
{
"title": "Peanuts"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray2)) { error in
XCTAssertEqual("\(error)", "hobbies is required, hobbies is required")
}

let invalidNestedArray3 = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football"
}
],
"allergies": [
{
"title": "Peanuts€"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray3)) { error in
XCTAssertEqual("\(error)", "allergies at index 0 title contains '€' (allowed: A-Z, a-z)")
}

let validNestedArray = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football"
}
],
}
"""
XCTAssertNoThrow(try User.validate(json: validNestedArray))
}

func testValidateNestedEachIndex() throws {
Expand Down