🔶
Swift Validators Reactive ExtensionsReactiveSwift
的 ValidatingProperty
是应用 SwiftValidators 的理想位置。 SwiftValidatorsReactiveExtensions
提供了一组扩展,使使用 ValidatingProperty
更容易。
内容
安装
SwiftValidatorsReactiveExtensions
可在 CocoaPods 上用于 iOS 9.0+、Xcode 8 和 Swift 3.0
pod 'SwiftValidatorsReactiveExtensions'
使用说明
使用方法
SwiftValidatorsReactiveExtensions
在 Validator
中提供了一个名为 reactive
的属性,它将每个可用的验证器映射到一个 ReactiveValidator
。一个 ReactiveValidator
可以验证一个符合 StringConvertible
的值,结果将是 ValidatorOutput<StringConvertible?, ValidationError>
。
ValidationError
是一个符合 Swift.Error
的枚举,为 SwiftValidators
中的所有可用验证器提供了一个案例,以及一个特殊案例 .notSpecified
,用于在错误未指定时。
Validator.reactive
.isEmail().apply("[email protected]") // returns .valid
Validator.reactive
.isEmail().apply("abcd") // returns .invalid(.isEmail)
有关如何调用每个验证器的更多示例,您可以查看 单元测试。
逻辑运算符
ReactiveValidator
允许将 combine
函数作为 static
函数和 instance
函数使用。该 combine
函数相当于逻辑与,意味着所有验证器必须为 .valid
,组合验证器才为 .valid
。
ReactiveValidator.combine(
Validator.reactive.isEmail(),
Validator.reactive.isLowercase()
) // variadic function
ReactiveValidator
.combine([
Validator.reactive.isEmail(),
Validator.reactive.isLowercase()
]) // array arguments
Validator.reactive
.isEmail()
.combine(with: Validator.reactive.isLowercase()) // instance function
映射
SwiftValidatorsReactiveExtensions
提供了一个 map
函数,将 ReactiveValidator
的 ValidatorOutput<StringConvertible?, ValidationError>
结果映射到 ValidatingProperty
所期望的精确的验证器输出。
email = ValidatingProperty<String?, ValidationError>(nil, { (value: String?) -> ValidatorOutput<String?, ValidationError> in
return ReactiveValidator.combine([
Validator.reactive.required(),
Validator.reactive.minLength(5),
Validator.reactive.maxLength(32),
Validator.reactive.isEmail()
])
.apply(value)
.map() { $0 as? String }
})
可用验证器
在 SwiftValidators
中可用的所有验证器。
MIT许可证
Copyright (c) George Kaimakas [email protected]
Permission is hereby granted, free of charge, to any person obtaining
acopy 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.