Swift Validator 是一个基于规则的 Swift 验证库。
UITextField
+ [Rule]
+ (可选的错误 UILabel
)放入 Validator
UITextField
+ ValidationError
从 Validator
出来Validator
按顺序评估 [Rule]
并在 Rule
失败时停止评估。# Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, "8.1"
use_frameworks!
pod 'SwiftValidator', '3.0.1'
将库安装到项目中
$ pod install
打开包含 .xcworkspace 文件的 Xcode 项目(不是常规的项目文件)
$ open MyProject.xcworkspace
如果您使用 Carthage,您需要将其添加到您的 Cartfile
github "jpotts18/SwiftValidator"
现在您可以导入 SwiftValidator 框架到您的文件中。
通过设置一个委托到视图控制器或其他对象初始化 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(delegate:self)
}
在您的视图控制器中实现验证委托
// ValidationDelegate methods
func validationSuccessful() {
// submit the form
}
func validationFailed(errors:[UITextField:ValidationError]) {
// turn the fields to red
for (field, error) in validator.errors {
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)
}
}
Swift Validator 由 Jeff Potter 编写和维护 @jpotts18。
git checkout -b my-new-feature
git commit -am 'Add some feature'
git push origin my-new-feature