Skip to content

Validation

Alexis Bridoux edited this page Nov 21, 2020 · 3 revisions

When declaring a field, you can add one or more validations on the received value. All the validations will be evaluated when calling validate() or validateAndAssign(), and an error will be thrown if the value is not validated.

To use a validation, you can simply declare it. A validation is available when it makes sense for the value type (.e.g. isEmail is only for String values).

// name: String?
let name = Field(\.name, validations: .notEmpty)
let name = Field(\.name, validations: .hasPrefix("Do"))
let name = Field(\.name, validations: .hasPrefix("Do"), .contains("remi"))

// score: Double
let score = Field(\.score, validations: .isIn(100...1000))

Other validations will be added in the future. Meanwhile, you can add your own validation, for example, to make sure a numeric value is greater than a given threshold:

extension Validation where Value: Numeric & Comparable {

    static func greaterThan(_ value: Value) -> Self {
        Validation {
            if value <= $0 {
                throw CoreDataCandyError.dataValidation(description: "Value \($0) is greater than \($0)")
            }
        }
    }
}

List

Here is the exhaustive list of currently available validations:

  • String: notEmpty, hasSuffix, hasPrefix, contains, doesNotContain, count, isEmail
  • Numeric & Comparable: isIn, greaterThan, greaterThanOrEqualTo, lesserThan, lesserThanOrEqualTo
  • ExpressibleByNilLiteral: notNil
Clone this wiki locally