测试已测试 | ✓ |
Lang语言 | SwiftSwift |
许可证 | MIT |
发布上次发布 | 2016年12月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Danilo Topalovic 维护。
很遗憾,没有找到这个软件的炫酷名字,所以我叫它验证器。
受到了 Zend\Validate 和 Eureka 的极大启发,我开始在这个组件上工作,并且我还在添加测试/验证器。如果您遇到任何问题或错误,请随时报告错误甚至为这个错误编写一个测试,以便在错误解决时使其再次良好。
请参阅 ExampleProject
如果您也缺少对表单输入进行过滤的一种类型,请参阅 SwiftFilter
查看 CocoaPods,以轻松将其安装到您的项目中
按如下方式将 SwiftValidate
添加到您的 Podfile
pod 'SwiftValidate', '~> 2.0.1'
然后,像往常一样,在您的目录中运行 pod install
所有验证器都可以完全独立使用,但 SwiftValidate 的一个主要优点是验证器是可以链式的。根据需要添加尽可能多的验证器到一个单一的链中,以正确验证您的值。
将 import SwiftValidate
添加到您的 View Controller。
然后,您就可以开始使用了。
let validatorChain = ValidatorChain() {
$0.stopOnFirstError = true
$0.stopOnException = true
} <~~ ValidatorRequired() {
$0.errorMessage = "Enter the value!"
} <~~ ValidatorEmpty() {
$0.allowNil = false
} <~~ ValidatorStrLen() {
$0.minLength = 3
$0.maxLength = 30
$0.errorMessageTooSmall = "My fancy own error message"
}
let myValue = "testValue"
let result = validatorChain.validate(myValue, context: nil)
let errors = validatorChain.errors
如果您要处理大量值(例如表单结果),您可以轻松地预定义一个ValidationIterator,并将其链接到多个表单字段名称的链中。
请参阅ValidationIteratorTests的提取
// form values given by some user
let formResults: [String: Any?] = [
"name": "John Appleseed",
"street": "1456 Sesame Street",
"zipcode": "01526",
"city": "Somewhere",
"country": nil
]
let validationIterator = ValidationIterator() {
$0.resultForUnknownKeys = true
}
// name, street, city
validationIterator.register(
chain: ValidatorChain() {
$0.stopOnException = true
$0.stopOnFirstError = true
}
<~~ ValidatorRequired()
<~~ ValidatorEmpty()
<~~ ValidatorStrLen() {
$0.minLength = 3
$0.maxLength = 50
},
forKeys: ["name", "street"]
)
// zipcode
validationIterator.register(
chain: ValidatorChain() {
$0.stopOnException = true
$0.stopOnFirstError = true
}
<~~ ValidatorRequired()
<~~ ValidatorStrLen() {
$0.minLength = 5
$0.maxLength = 5
}
<~~ ValidatorNumeric() {
$0.allowString = true
$0.allowFloatingPoint = false
},
forKey: "zipcode"
)
// country (not required but if present between 3 and 50 chars)
validationIterator.register(
chain: ValidatorChain() {
$0.stopOnException = true
$0.stopOnFirstError = true
}
<~~ ValidatorStrLen() {
$0.minLength = 3
$0.maxLength = 50
},
forKey: "country"
)
let validationResult = validationIterator.validate(formResults)
let cityInError = validationIterator.isInError("city")
有关更多示例和说明,请参阅WiKi
由于其他所有验证器默认允许nil,因此可以将此验证器作为第一个添加,以检查值是否存在。它还配备了回调,您可以在其中根据值和上下文决定是否满足要求。
配置
配置
value | type | default | description |
---|---|---|---|
requirementCondition | closure | ? | optional custom requirement check |
错误信息
errorMessage
- 当值nil时的错误信息检验给定的值是否不是一个空字符串
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | 值可以是nil |
错误信息
errorMessage
- 当值是空时显示的错误信息检验给定值在strlen中的最小值和最大值之间
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | 值可以是nil |
minLength | Int | 3 | 字符串的最小长度 |
maxLength | Int | 30 | 字符串的最大长度 |
minInclusive | Bool | true | 在值中的最小范围(包含) |
maxInclusive | Bool | true | 在值中的最大范围(包含) |
错误信息
errorMessageTooSmall: String
- 当字符串不够长时显示的错误信息errorMessageTooLarge: String
- 当字符串太长时显示的错误信息验证给定的值是否只包含从给定字符集中的字符
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | 值可以是nil |
allowEmpty | Bool | false | 值可以是空的 |
charset | NSCharacterSet | ! | 比较的字符集 |
错误信息
errorMessageStringDoesNotFit: String
- (可选)验证给定的值是否仅由字母数字字符组成
This is a specialization of ValidatorCharset()
验证给定的电子邮件地址
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | 值可以是nil |
validateLocalPart | Bool | true | 将验证电子邮件地址的本地部分 |
validateHostnamePart | Bool | true | 将验证电子邮件地址的主机名部分 |
validateTopLevelDomain | Bool | true | 地址必须有顶级域名 |
strict | Bool | true | 还将验证各部分长度 |
错误信息
errorMessageInvalidAddress
- 地址无效errorMessageInvalidLocalPart
- 本地部分(@之前)无效errorMessageInvalidHostnamePart
- 主机名无效errorMessagePartLengthExceeded
- 部分长度超限验证给定的字符串是否与用户定义的正则表达式匹配
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
pattern | String | - | 匹配的模式 |
options | NSRegularExpressionOptions | 0 | 正则表达式选项 |
matchingOptions | NSMatchingOptions | 0 | 匹配选项 |
错误信息
errorMessageValueIsNotMatching
- 值与给定模式不匹配验证给定值是否为有效数字
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
allowString | Bool | true | 值可以是数值字符串 |
allowFloatingPoint | Bool | true | 值可以是浮点数 |
错误信息
errorMessageNotNumeric
- 值不是数字验证数值是否在两个预定义值之间
通用
let validator = ValidatorBetween<Double>() {
$0.minValue = 1.0
$0.maxValue = 99.1
}
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
allowString | Bool | true | 值可以是数值字符串 |
minValue | TYPE | 0 | 最小值 |
maxValue | TYPE | 0 | 最大值 |
minInclusive | Bool | true | 最小值包含(使用 >= 而不是 >) |
maxInclusive | Bool | true | 最大值包含 |
错误信息
errorMessageInvalidType
- 给定的类型无效 [-应抛出异常-]errorMessageNotBetween
- 值不在预定义值之间验证给定值是否大于预定义值
通用
let validator = ValidatorGreaterThan<Double>() {
$0.min = 1.0
}
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
min | TYPE | 0 | 需要超过的值 |
包含 | Bool | true | 值本身包含 |
错误信息
errorMessageInvalidType
- 给定的类型无效 [-应抛出异常-]errorMessageNotGreaterThan
- 值不足以大于验证给定值是否小于预定义值
通用
let validator = ValidatorSmallerThan<Double>() {
$0.max = 10.0
}
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
max | TYPE | 0 | 需要超过的值 |
包含 | Bool | true | 值本身包含 |
错误信息
errorMessageInvalidType
- 给定的类型无效 [-应抛出异常-]errorMessageNotSmallerThan
- 值不足以小于验证给定的日期是否有效
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
dateFormat | String | 0 | 解析的日期格式 |
错误信息
errorMessageInvalidDate
- 给定的日期无效验证给定的日期(NSDate 或 String)是否在预定义日期之间
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
min | NSDate | ! | 最小日期 |
max | NSDate | ! | 最大日期 |
minInclusive | Bool | true | 最小值包含(使用 >= 而不是 >) |
maxInclusive | Bool | true | 最大值包含 |
dateFormatter | NSDateFormatter | ! | 如果期望字符串,用于解析字符串的日期格式器 |
错误信息
errorMessageNotBetween
- 日期不在预定义日期之间执行给定的回调并与结果一起工作
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
回调 | closure | ! | 要验证的回调 |
回调如下
let validator = ValidatorCallback() {
$0.callback = {(validator: ValidatorCallback, value: Any?, context: [String : Any?]?) in
if nil == value {
/// you can throw
throw NSError(domain: "my domain", code: 1, userInfo: [NSLocalizedDescriptionKey: "nil!!"])
}
return (false, "My Error Message")
/// return (true, nil)
}
}
验证给定的值是否包含在预定义的数组中
通用
let validator = ValidatorInArray<String>() {
$0.array = ["Andrew", "Bob", "Cole", "Dan", "Edwin"]
}
let validator = ValidatorInArray<Double>() {
$0.allowNil = false
$0.array = [2.4, 3.1, 9.8, 4.9, 2.0]
}
配置
value | type | default | description |
---|---|---|---|
allowNil | Bool | true | nil是被允许的 |
数组 | [TYPE] | [] | 包含预定义值的数组 |
错误信息
errorMessageItemIsNotContained
- 给定的值不在数组中非通用
class MyValidator: BaseValidator, ValidatorProtocol {
required public init( _ initializer: @noescape(MyValidator) -> () = { _ in }) {
super.init()
initializer(self)
}
override func validate<T: Any>( _ value: T?, context: [String: Any?]?) throws -> Bool {
/// ...
}
}
通用
class MyGenericValidator<TYPE where TYPE: Equatable>: ValidatorProtocol, ValidationAwareProtocol {
required public init( _ initializer: @noescape(MyGenericValidator) -> () = { _ in }) {
initializer(self)
}
public func validate<T: Any>( _ value: T?, context: [String: Any?]?) throws -> Bool {
/// ...
}
}