-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDependentValidationRule.swift
More file actions
65 lines (57 loc) · 2.14 KB
/
DependentValidationRule.swift
File metadata and controls
65 lines (57 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// Validator
// Copyright © 2025 Space Code. All rights reserved.
//
/// A validation rule that depends on another field's value to determine which rule to apply.
///
/// # Example:
/// ```swift
/// let countryField = FormField(value: "US")
/// let phoneField = FormField(
/// value: "",
/// rules: [
/// DependentValidationRule(
/// dependsOn: countryField,
/// error: "Invalid phone number",
/// ruleProvider: { country in
/// if country == "US" {
/// return USPhoneRule()
/// } else {
/// return InternationalPhoneRule()
/// }
/// }
/// )
/// ]
/// )
/// ```
public struct DependentValidationRule<DependentInput, Input>: IValidationRule {
// MARK: Properties
/// The error message or error object to return if validation fails.
public let error: IValidationError
/// A closure that returns the value of the field this rule depends on.
private let dependentField: () -> DependentInput
/// A closure that takes the dependent field's value and returns the appropriate validation rule.
private let ruleProvider: (DependentInput) -> any IValidationRule<Input>
// MARK: Initialization
/// Creates a dependent validation rule.
///
/// - Parameters:
/// - dependsOn: A closure that returns the value of the field this rule depends on.
/// - error: The error message or error object to return if validation fails.
/// - ruleProvider: A closure that takes the dependent field's value and returns the appropriate validation rule.
public init(
dependsOn: @escaping @autoclosure () -> DependentInput,
error: IValidationError,
ruleProvider: @escaping (DependentInput) -> any IValidationRule<Input>
) {
dependentField = dependsOn
self.error = error
self.ruleProvider = ruleProvider
}
// MARK: IValidationRule
public func validate(input: Input) -> Bool {
let dependentValue = dependentField()
let rule = ruleProvider(dependentValue)
return rule.validate(input: input)
}
}