-
Notifications
You must be signed in to change notification settings - Fork 0
/
Validator.swift
51 lines (39 loc) · 1.45 KB
/
Validator.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import Foundation
import UIKit
@objc protocol ValidationDelegate {
func validationWasSuccessful()
func validationFailed(errors:[UITextField:ValidationError])
}
class Validator {
var errors:[UITextField:ValidationError] = [:]
var validations:[UITextField:ValidationRule] = [:]
init(){}
func registerField(textField:UITextField, rules:[Rule]) {
validations[textField] = ValidationRule(textField: textField, rules: rules, errorLabel: nil)
}
/*func registerField(textField:UITextField, errorLabel:UILabel, rules:[Rule]) {
validations[textField] = ValidationRule(textField: textField, rules:rules, errorLabel:errorLabel)
}*/
func validateAll(delegate:ValidationDelegate) {
for field in validations.keys {
if let currentRule:ValidationRule = validations[field] {
if var error:ValidationError = currentRule.validateField() {
if (currentRule.errorLabel != nil) {
error.errorLabel = currentRule.errorLabel
}
errors[field] = error
} else {
errors.removeValueForKey(field)
}
}
}
if errors.isEmpty {
delegate.validationWasSuccessful()
} else {
delegate.validationFailed(errors)
}
}
func clearErrors(){
self.errors = [:]
}
}