Added validate function with callback + tests

This commit is contained in:
Cameron McCord 2015-04-30 17:55:06 -06:00
parent 8d25feda3f
commit dfa5c257ce
2 changed files with 29 additions and 0 deletions

View File

@ -57,6 +57,21 @@ public class Validator {
}
}
public func validate(callback:(errors:[UITextField:ValidationError])->Void) -> Void {
for field in validations.keys {
if let currentRule:ValidationRule = validations[field] {
if var error:ValidationError = currentRule.validateField() {
errors[field] = error
} else {
errors.removeValueForKey(field)
}
}
}
callback(errors: errors)
}
func clearErrors() {
self.errors = [:]
}

View File

@ -164,4 +164,18 @@ class ValidatorTests: XCTestCase {
UNREGISTER_VALIDATOR.unregisterField(UNREGISTER_TXT_FIELD)
XCTAssert(UNREGISTER_VALIDATOR.validations[UNREGISTER_TXT_FIELD] == nil, "Textfield should unregister")
}
// MARK: Validate Functions
func testValidateWithCallback() {
REGISTER_VALIDATOR.registerField(REGISTER_TXT_FIELD, rules: [EmailRule()])
REGISTER_TXT_FIELD.text = VALID_EMAIL
REGISTER_VALIDATOR.validate { (errors) -> Void in
XCTAssert(errors.count == 0, "Should not come back with errors")
}
REGISTER_TXT_FIELD.text = INVALID_EMAIL
REGISTER_VALIDATOR.validate { (errors) -> Void in
XCTAssert(errors.count == 1, "Should come back with 1 error")
}
}
}