验证

一个可以验证其包装属性的属性包装器。

当包装的值更改时,@Validate 将针对该值运行提供的验证。

验证后,isValiderrors 属性可以提供验证结果。

Validate 框架包含许多内置验证,例如存在性、计数和格式。所有这些都适用于各种类型。

要求

安装

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/reddavis/Validate", from: "2.0.0")
]

文档

API 参考

用法

import SwiftUI
import Validate


struct ContentView: View {
    @Validate(.presence()) var name: String = ""
    
    var body: some View {
        VStack(spacing: 60) {
            VStack {
                TextField("Name", text: self.$name.binding)
                    .textFieldStyle(.roundedBorder)
                    .padding()
                
                VStack {
                    ForEach(self.$name.errors.localizedDescriptions, id: \.self) { message in
                        Text(message)
                            .foregroundColor(.red)
                            .font(.footnote)
                    }
                }
            }
            
            Button("Save") {
                print(self.name)
            }
            .buttonStyle(.bordered)
        }
    }
}

内置验证

Validate 包含多个验证

构建验证

您不仅限于使用内置验证,还可以通过使用 Validation 构建器来构建自己的验证。

以下是内置存在性验证的构建方式

public extension Validation {
    /// Validate an optional value is present.
    ///
    /// If the value is nil, it is considered invalid.
    /// - Parameters:
    ///   - message: A custom error message.
    /// - Returns: A Validation instance.
    static func presence<T>(
        message: String? = nil
    ) -> Validation<Optional<T>> {
        .init { value in
            if value == nil {
                throw ValidationError.build(message: message)
            }
        }
    }
}

其他库

查看我的其他一些库