ValidatedPropertyKit 0.0.5

ValidatedPropertyKit 0.0.5

Sven Tiigi 维护。



  • 作者
  • Sven Tiigi

ValidatedPropertyKit Logo

Swift 5.1 CI Status Version Platform
Carthage Compatible SPM Documentation Twitter


ValidatedPropertyKit 使您能够轻松通过属性包装器的强大功能校验您的属性。
查看属性包装器提案


struct LoginView: View {
    
    @Validated(!.isEmpty && .isEmail)
    var mailAddress = String()
    
    @Validated(.range(8...))
    var password = String()
    
    var body: some View {
        List {
            TextField("E-Mail", text: self.$mailAddress)
            TextField("Password", text: self.$password)
            Button(
                action: {
                    print("Login", self.mailAddress, self.password)
                },
                label: {
                    Text("Submit")
                }
            )
            .validated(
                self._mailAddress,
                self._password
            )
        }
    }
    
}

特性

  • 轻松验证您的属性👮
  • 预定义验证🚦
  • 组合验证的逻辑操作符🔗
  • 按需定制和配置💪

安装

CocoaPods

ValidatedPropertyKit 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中

pod 'ValidatedPropertyKit'

Carthage

Carthage 是一个去中心化的依赖关系管理器,它构建您的依赖关系并为您提供了二进制框架。

要使用 Carthage 将 ValidatedPropertyKit 集成到您的 Xcode 项目中,在您的 Cartfile 中指定它

github "SvenTiigi/ValidatedPropertyKit"

运行 carthage update 以构建框架,并将构建好的 ValidatedPropertyKit.framework 拖到您的 Xcode 项目中。

在您的应用程序目标“构建阶段”设置选项卡中,单击“+”图标,选择“新建运行脚本阶段”,并将框架路径添加到Carthage 入门步骤 4、5 和 6 中所述

Swift 包管理器

要使用 Apple 的 Swift 包管理器 进行集成,请在您的 Package.swift 中添加以下依赖项

dependencies: [
    .package(url: "https://github.com/SvenTiigi/ValidatedPropertyKit.git", from: "0.0.5")
]

或者导航到您的 Xcode 项目,然后选择 Swift Packages,单击“+”图标,搜索 ValidatedPropertyKit

手动

如果您不想使用上述任何依赖项管理器,您可以将 ValidatedPropertyKit 手动集成到项目中。只需将 Sources 文件夹拖到您的 Xcode 项目中。

Validated👮‍♂️

@Validated 属性允许您在您的属性声明旁边指定验证。

☝️@Validated 支持 SwiftUI 视图更新,并且与 @State 的方式基本相同。

@Validated(!.isEmpty)
var username = String()

@Validated(.hasPrefix("https"))
var avatarURL: String?

如果 @Validated 适用于如 String? 这样的可选类型,您可以指定当值是 nil 时验证应该失败还是成功。

@Validated(
   .isURL && .hasPrefix("https"), 
   nilValidation: .constant(false)
)
var avatarURL: String?

默认情况下,nilValidation 参数设置为 .constant(false)

此外,SwiftUI.View 扩展 validated() 允许您根据 @Validated 属性禁用或启用特定的 SwiftUI.View。如果至少有一个传递给 validated()@Validated 属性评估结果为 false,则 validated() 函数将禁用该 SwiftUI.View

@Validated(!.isEmpty && .contains("@"))
var mailAddress = String()
    
@Validated(.range(8...))
var password = String()

Button(
   action: {},
   label: { Text("Submit") }
)
.validated(self._mailAddress && self._password)

使用下划线符号,您将 @Validated 属性包装器传递给 validated() 函数。

验证🚦

每个 @Validated 属性都将初始化为一个 Validation,该验证可以初始化为一个简单的闭包,该闭包必须返回一个 Bool 值。

@Validated(.init { value in
   value.isEmpty
})
var username = String()

因此,ValidatedPropertyKit附带了许多针对不同类型和协议的内置便捷函数。

@Validated(!.contains("Android", options: .caseInsensitive))
var favoriteOperatingSystem = String()

@Validated(.equals(42))
var magicNumber = Int()

@Validated(.keyPath(\.isEnabled, .equals(true)))
var object = MyCustomObject()

前往预定义验证部分了解更多信息。

此外,您可以通过条件遵守来扩展 Validation,从而轻松声明您自己的验证。

extension Validation where Value == Int {

    /// Will validate if the Integer is the meaning of life
    static var isMeaningOfLife: Self {
        .init { value in
            value == 42
        }
    }

}

并将其应用于您的验证属性。

@Validated(.isMeaningOfLife)
var number = Int()

isValid

您可以通过使用下划线符号直接访问 @Validated 属性包装器来在任何时候访问 isValid 状态。

@Validated(!.isEmpty)
var username = String()

username = "Mr.Robot"
print(_username.isValid) // true

username = ""
print(_username.isValid) // false

验证运算符🔗

验证运算符允许您像操作布尔值一样组合多个验证。

// Logical AND
@Validated(.hasPrefix("https") && .hasSuffix("png"))
var avatarURL = String()

// Logical OR
@Validated(.hasPrefix("Mr.") || .hasPrefix("Mrs."))
var name = String()

// Logical NOT
@Validated(!.contains("Android", options: .caseInsensitive))
var favoriteOperatingSystem = String()

预定义验证

ValidatedPropertyKit附带了许多预定义的常用验证,您可利用它们为您的验证属性指定验证。

关键路径

keyPath 验证允许您为属性注解指定的关键路径指定验证。

@Validated(.keyPath(\.isEnabled, .equals(true)))
var object = MyCustomObject()

字符串

字符串属性可以通过多种方式验证,如 containshasPrefix 以及甚至 RegularExpressions

@Validated(.isEmail)
var string = String()

@Validated(.contains("Mr.Robot"))
var string = String()

@Validated(.hasPrefix("Mr."))
var string = String()

@Validated(.hasSuffix("OS"))
var string = String()

@Validated(.regularExpression("[0-9]+$"))
var string = String()

等价

等价类型可以与指定值进行比较。

@Validated(.equals(42))
var number = Int()

序列

类型为 Sequence 的属性可以通过 containsstartsWith 验证进行验证。

@Validated(.contains("Mr.Robot", "Elliot"))
var sequence = [String]()

@Validated(.startsWith("First Entry"))
var sequence = [String]()

集合

每个 Collection 类型都提供 isEmpty 验证和范围验证,您可以轻松地声明有效容量。

@Validated(!.isEmpty)
var collection = [String]()

@Validated(.range(1...10))
var collection = [String]()

可比

可比类型可以使用所有常用的比较运算符进行验证。

@Validated(.less(50))
var comparable = Int()

@Validated(.lessOrEqual(50))
var comparable = Int()

@Validated(.greater(50))
var comparable = Int()

@Validated(.greaterOrEqual(50))
var comparable = Int()

推荐于

贡献

非常欢迎贡献🙌

许可

ValidatedPropertyKit
Copyright (c) 2021 Sven Tiigi [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.