Swift Validator 是一个基于规则的 Swift 验证库。
UITextField
+ [Rule]
+(可选的 UILabel
错误)进入 Validator
UITextField
+ ValidationError
从 Validator
输出Validator
按顺序评估 [Rule]
,并在 Rule
失败时停止评估。通过将一个视图控制器或其他对象设置为由代理初始化 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
validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule()])
// 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}")])
}
在按钮点击或其他您想触发的操作中验证字段。
@IBAction func signupTapped(sender: AnyObject) {
validator.validateAll(delegate:self)
}
在视图控制器中实现验证代理
// ValidationDelegate methods
func validationWasSuccessful() {
// 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
}
}
我们将创建一个 SSNRule
类,以展示如何创建自己的验证。美国社会保障号码 (或 SSN) 是一个由 XXX-XX-XXXX 组成的字段。
创建一个实现规则协议的类
class SSNVRule: Rule {
let REGEX = "^\\d{3}-\\d{2}-\\d{4}$"
init(){}
// allow for custom variables to be passed
init(regex:String){
self.REGEX = regex
}
func validate(value: String) -> Bool {
if let ssnTest = NSPredicate(format: "SELF MATCHES %@", REGEX) {
if ssnTest.evaluateWithObject(value) {
return true
}
return false
}
}
func errorMessage() -> String{
return "Not a valid SSN"
}
}
Swift Validator 由 Jeff Potter 编写和维护@jpotts18。
git checkout -b my-new-feature
git commit -am '添加一些功能'
git push origin my-new-feature