-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFormValidationViewModifier.swift
More file actions
52 lines (41 loc) · 1.39 KB
/
FormValidationViewModifier.swift
File metadata and controls
52 lines (41 loc) · 1.39 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
//
// Validator
// Copyright © 2023 Space Code. All rights reserved.
//
import SwiftUI
import ValidatorCore
public struct FormValidationViewModifier<ErrorView: View>: ViewModifier {
// MARK: Properties
/// The result of the validation.
@State private var validationResult: ValidationResult = .valid
/// A container for form validation logic.
private let validationContainer: any IFormValidationContainer
/// A custom parameter attribute that constructs views from closures.
@ViewBuilder private let content: ([any IValidationError]) -> ErrorView
// MARK: Initialization
public init(
validationContainer: any IFormValidationContainer,
@ViewBuilder content: @escaping ([any IValidationError]) -> ErrorView
) {
self.validationContainer = validationContainer
self.content = content
}
// MARK: ViewModifier
public func body(content: Content) -> some View {
VStack(alignment: .leading) {
content
validationMessageView
}.onReceive(validationContainer.publisher) { result in
validationResult = result
}
}
// MARK: Private
private var validationMessageView: some View {
switch validationResult {
case .valid:
EmptyView().eraseToAnyView()
case let .invalid(errors):
content(errors).eraseToAnyView()
}
}
}