1
- import Core
2
-
3
1
/// Capable of being validated.
4
- public protocol Validatable : Codable , ValidationDataRepresentable {
5
- /// The validations that will run when `.validate()`
6
- /// is called on an instance of this class.
2
+ ///
3
+ /// final class User: Validatable, Reflectable {
4
+ /// var id: Int?
5
+ /// var name: String
6
+ /// var age: Int
7
+ ///
8
+ /// init(id: Int? = nil, name: String, age: Int) {
9
+ /// self.id = id
10
+ /// self.name = name
11
+ /// self.age = age
12
+ /// }
13
+ ///
14
+ /// static var validations: Validations = [
15
+ /// key(\.name): IsCount(5...) && IsAlphanumeric(), // Is at least 5 letters and alphanumeric
16
+ /// key(\.age): IsCount(18...) // 18 or older
17
+ /// ]
18
+ /// }
19
+ ///
20
+ public protocol Validatable {
21
+ /// The validations that will run when `.validate()` is called on an instance of this class.
7
22
static var validations : Validations { get }
8
23
}
9
24
10
25
extension Validatable {
11
- /// See ValidationDataRepresentable.makeValidationData()
12
- public func makeValidationData( ) -> ValidationData {
13
- return . validatable( self )
14
- }
15
- }
16
-
17
- extension Validatable {
18
- /// Validates the model, throwing an error
19
- /// if any of the validations fail.
20
- /// note: non-validation errors may also be thrown
21
- /// should the validators encounter unexpected errors.
26
+ /// Validates the model, throwing an error if any of the validations fail.
27
+ /// - note: non-validation errors may also be thrown should the validators encounter unexpected errors.
22
28
public func validate( ) throws {
23
29
var errors : [ ValidationError ] = [ ]
24
30
25
31
for (key, validation) in Self . validations. storage {
26
32
/// fetch the value for the key path and
27
33
/// convert it to validation data
28
- let data = ( self [ keyPath : key. keyPath ] as ValidationDataRepresentable ) . makeValidationData ( )
34
+ let data = try getValidationData ( at : key)
29
35
30
36
/// run the validation, catching validation errors
31
37
do {
@@ -37,14 +43,15 @@ extension Validatable {
37
43
}
38
44
39
45
if !errors. isEmpty {
40
- throw ValidatableError ( errors)
46
+ throw ValidateError ( errors)
41
47
}
42
48
}
43
49
}
44
50
45
- /// a collection of errors thrown by validatable
46
- /// models validations
47
- struct ValidatableError : ValidationError {
51
+ // MARK: Private
52
+
53
+ /// a collection of errors thrown by validatable models validations
54
+ fileprivate struct ValidateError : ValidationError {
48
55
/// the errors thrown
49
56
var errors : [ ValidationError ]
50
57
@@ -61,7 +68,7 @@ struct ValidatableError: ValidationError {
61
68
}
62
69
63
70
/// creates a new validatable error
64
- public init ( _ errors: [ ValidationError ] ) {
71
+ init ( _ errors: [ ValidationError ] ) {
65
72
self . errors = errors
66
73
self . path = [ ]
67
74
}
0 commit comments