ValidationKit

一个轻量级的 Swift 库,用于验证和规范化用户输入,例如在表单中。

文档

ValidationKit 的文档可以在 GitHub Pages 上找到。 文档使用 DocC 编写,并在 Swift 包中包含了一个文档目录。

用法

使用内置的验证器

import ValidationKit

// Validators can be combined using the operators `&&` and `||`
let tweetValidator: Validator = .notEmpty && .maxLength(280)

let tweet = "Hello, world!"
let result = tweetValidator.validate(input: tweet)

switch result {
case .valid(let value):
  print("Tweet '\(value)' is valid")
case .invalid(let error):
  print(String(format: "Tweet did not validate: %@", error.localizedDescription))
}

内置的验证器包括:

实现自定义验证器

可以按照以下方式实现自定义验证器。 该示例使用了正则表达式,但您当然可以自由使用任何您想要的逻辑。

public extension Validator {
  static var isDutchPostalCode: Validator<String, String> {
    Validator<String, String> { input in
      if let range = input.range(of: #"^\d{4}\s?[a-zA-Z]{2}$"#, options: .regularExpression) {
        let output = String(input[range])
        return .valid(output)
      } else {
        return .invalid(.invalidDutchPostalCode)
      }
    }
  }
}

public extension ValidationError {
  static let invalidDutchPostalCode = ValidationError(localizedDescription: NSLocalizedString("Invalid Dutch postal code", comment: "Validation error text"))
}

然后我们可以这样使用它

let postalCodeValidator: Validator = .notEmpty && .isDutchPostalCode
let result = postalCodeValidator.validate(input: "2516 AH") // Equals ValidationResult.valid("2516 AH")

验证器的输入不必与其输出的类型相同。 例如,此验证器将字符串转换为数字数组(0-9 的整数)。

extension Validator {
  /// Validates whether a string consists of a sequence of digits (0-9).
  static var numericCode: Validator<String, [Int]> {
    Validator<String, [Int]> { input in
      let numericCode: [Int] = input
        .map(String.init) // Convert the string to individual characters first
        .compactMap(Int.init)

      if numericCode.count == input.count {
        return .valid(numericCode)
      } else {
        return .invalid(.notNumericCode)
      }
    }
  }
}

extension ValidationError {
  static let notNumericCode = ValidationError(localizedDescription: NSLocalizedString("Not a numeric code", comment: "Validation error text"))
}

要验证一个 8 位数的代码,我们可以这样使用它

let validator: Validator = .exactLength(8) && .numericCode
let result = validator.validate(input: "13374242)
result.isValid // True
result.value // [1, 3, 3, 7, 4, 2, 4, 2]

国际化

此库包含英语和荷兰语的本地化字符串。 欢迎提交请求,添加对其他语言的支持。

如果您希望对某个验证使用不同的错误文本,则必须编写自己的验证器和验证错误。 有关如何执行此操作的示例,请参见Validators.swiftValidationError.swift文件。

版本发布

许可证 & 鸣谢

ValidationKit 由 Mathijs BernsonTim van Steenis 编写。

它在 MIT 许可证下可用,因此可以随意在商业和非商业项目中使用它。