@@ -53,7 +53,8 @@ override func viewDidLoad() {
53
53
validator.registerField (fullNameTextField, rules : [RequiredRule (), FullNameRule ()])
54
54
55
55
// You can pass in error labels with your rules
56
- validator.registerField (emailTextField, errorLabel : emailErrorLabel, rules : [RequiredRule (), EmailRule ()])
56
+ // You can pass in custom error messages to regex rules (such as ZipCodeRule and EmailRule)
57
+ validator.registerField (emailTextField, errorLabel : emailErrorLabel, rules : [RequiredRule (), EmailRule (message : " Invalid email" )])
57
58
58
59
// You can validate against other fields using ConfirmRule
59
60
validator.registerField (emailConfirmTextField, errorLabel : emailConfirmErrorLabel, rules : [ConfirmationRule (confirmField : emailTextField)])
@@ -101,31 +102,16 @@ func validationFailed(errors:[UITextField:ValidationError]) {
101
102
102
103
We will create a ``` SSNRule ``` class to show how to create your own Validation. A United States Social Security Number (or SSN) is a field that consists of XXX-XX-XXXX.
103
104
104
- Create a class that implements the Rule protocol
105
+ Create a class that inherits from RegexRule
105
106
106
107
``` swift
107
108
108
- class SSNVRule : Rule {
109
- let REGEX = " ^\\ d{3}-\\ d{2}-\\ d{4}$"
110
-
111
- init (){}
112
-
113
- // allow for custom variables to be passed
114
- init (regex :String ){
115
- self .REGEX = regex
116
- }
117
-
118
- func validate (value : String ) -> Bool {
119
- if let ssnTest = NSPredicate (format : " SELF MATCHES %@" , REGEX) {
120
- if ssnTest.evaluateWithObject (value) {
121
- return true
122
- }
123
- return false
124
- }
125
- }
126
-
127
- func errorMessage () -> String {
128
- return " Not a valid SSN"
109
+ class SSNVRule : RegexRule {
110
+
111
+ static let regex = " ^\\ d{3}-\\ d{2}-\\ d{4}$"
112
+
113
+ convenience init (message : String = " Not a valid SSN" ){
114
+ self .init (regex : SSNVRule.regex , message : message)
129
115
}
130
116
}
131
117
```
0 commit comments