QuanderSwiftValidator 5.1.0

QuanderSwiftValidator 5.1.0

测试已测试
Lang语言 SwiftSwift
许可证 MIT
Released上次发布2017年9月
SwiftSwift 版本3.0
SPM支持 SPM

Sean Howard 维护。




  • Jeff Potter

SwiftValidator

Swift Validator 是一个基于规则的 Swift 验证库。

Swift Validator

核心概念

  • UITextField + [Rule] + (可选的 error UILabel) 进入 Validator
  • UITextField + ValidationErrorValidator 退出
  • Validator 按顺序评估 [Rule],并在有 Rule 失败时停止评估。

安装

# Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, "8.1"

use_frameworks!

# Swift 3
# Extended beyond UITextField
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :branch => 'master'

# Swift 2.1
# Extended beyond UITextField
# Note: Installing 4.x.x will break code from 3.x.x
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '4.0.0'

# Swift 2.1 (limited to UITextField validation)
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '3.0.5'

将安装到您的项目中

$ pod install

从 .xcworkspace 文件打开您的项目(而不是常规的项目文件)

$ open MyProject.xcworkspace

如果您正在使用 Carthage,则需要将其添加到您的 Cartfile

github "jpotts18/SwiftValidator"

使用

现在您可以将 SwiftValidator 框架导入到您的文件中。

通过将一个 View Controller 或其他对象设置为代理来初始化 Validator

// ViewController.swift
let validator = Validator()

注册要验证的字段

override func viewDidLoad() {
	super.viewDidLoad()

	// Validation Rules are evaluated from left to right.
	validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])
	
	// You can pass in error labels with your rules
	// You can pass in custom error messages to regex rules (such as ZipCodeRule and EmailRule)
	validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])
	
	// You can validate against other fields using ConfirmRule
	validator.registerField(emailConfirmTextField, errorLabel: emailConfirmErrorLabel, rules: [ConfirmationRule(confirmField: emailTextField)])
	
	// You can now pass in regex and length parameters through overloaded contructors
	validator.registerField(phoneNumberTextField, errorLabel: phoneNumberErrorLabel, rules: [RequiredRule(), MinLengthRule(length: 9)])
	validator.registerField(zipcodeTextField, errorLabel: zipcodeErrorLabel, rules: [RequiredRule(), ZipCodeRule(regex : "\\d{5}")])

	// You can unregister a text field if you no longer want to validate it
	validator.unregisterField(fullNameTextField)
}

在按钮点击或其他任何方式触发它时验证字段。

@IBAction func signupTapped(sender: AnyObject) {
	validator.validate(self)
}

在您的 View Controller 中实现验证代理

// ValidationDelegate methods

func validationSuccessful() {
	// submit the form
}

func validationFailed(errors:[(Validatable ,ValidationError)]) {
	// turn the fields to red
	for (field, error) in errors {
		if let field = field as? UITextField {
			field.layer.borderColor = UIColor.redColor().CGColor
			field.layer.borderWidth = 1.0		
		}
		error.errorLabel?.text = error.errorMessage // works if you added labels
		error.errorLabel?.hidden = false
	}
}

单字段验证

在某些情况下,您可能需要使用单字段验证。在像控制响应者这样的场合可能会很有用。

// Don't forget to use UITextFieldDelegate
// and delegate yourTextField to self in viewDidLoad()
func textFieldShouldReturn(textField: UITextField) -> Bool {
    validator.validateField(textField){ error in
        if error == nil {
            // Field validation was successful
        } else {
            // Validation error occurred
        }
    }
    return true
}

自定义验证

我们将创建一个 SSNRule 类来展示如何创建自己的验证。美国的社保号码(或 SSN)是一个由 XXX-XX-XXXX 组成的字段。

创建一个从 RegexRule 继承的类

class SSNVRule: RegexRule {

    static let regex = "^\\d{3}-\\d{2}-\\d{4}$"
	
    convenience init(message : String = "Not a valid SSN"){
	self.init(regex: SSNVRule.regex, message : message)
    }
}

文档

在此 (通过 @jazzydocs)查看文档。

鸣谢

Swift Validator 是由 Jeff Potter 编写和维护的 @jpotts18。David Patterson @dave_tw12 积极作为协作者工作。特别感谢 Deniz Adalar 为 UITextField 之外添加验证。

贡献力量

  1. 将其进行派生
  2. 创建你的功能分支 git checkout -b my-new-feature
  3. 提交你的更改 git commit -am '添加一些功能'
  4. 推送到分支 git push origin my-new-feature
  5. 创建一个新的 Pull Request
  6. 确保代码覆盖率至少为 70%