Merge pull request #63 from mathielo/single_field_validation

Single field validation
This commit is contained in:
Jeff Potter 2016-02-03 21:34:36 -07:00
commit d080a6c3cb
4 changed files with 66 additions and 0 deletions

View File

@ -108,6 +108,26 @@ func validationFailed(errors:[UITextField:ValidationError]) {
```
### Single Field Validation
You may use single field validation in some cases. This could be useful in situations such as controlling responders:
```swift
// 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
}
```
## Custom Validation
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.

View File

@ -47,6 +47,26 @@ public class Validator {
}
}
// MARK: Public functions
public func validateField(textField: UITextField, callback: (error:ValidationError?) -> Void){
if let fieldRule = validations[textField] {
if let error = fieldRule.validateField() {
if let transform = self.errorStyleTransform {
transform(validationError: error)
}
callback(error: error)
} else {
if let transform = self.successStyleTransform {
transform(validationRule: fieldRule)
}
callback(error: nil)
}
} else {
callback(error: nil)
}
}
// MARK: Using Keys
public func styleTransformers(success success:((validationRule:ValidationRule)->Void)?, error:((validationError:ValidationError)->Void)?) {

View File

@ -211,6 +211,18 @@ class SwiftValidatorTests: XCTestCase {
}
}
func testValidateSingleField() {
REGISTER_VALIDATOR.registerField(REGISTER_TXT_FIELD, rules: [EmailRule()])
REGISTER_TXT_FIELD.text = VALID_EMAIL
REGISTER_VALIDATOR.validateField(REGISTER_TXT_FIELD) { error in
XCTAssert(error == nil, "Should not present error")
}
REGISTER_TXT_FIELD.text = INVALID_EMAIL
REGISTER_VALIDATOR.validateField(REGISTER_TXT_FIELD) { error in
XCTAssert(error?.errorMessage.characters.count > 0, "Should state 'invalid email'")
}
}
// MARK: Validate error field gets it's text set to the error, if supplied
func testNoErrorMessageSet() {

View File

@ -78,4 +78,18 @@ class ViewController: UIViewController , ValidationDelegate, UITextFieldDelegate
func hideKeyboard(){
self.view.endEditing(true)
}
// MARK: Validate single field
// Don't forget to use UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
validator.validateField(textField){ error in
if error == nil {
// Field validation was successful
} else {
// Validation error occurred
}
}
return true
}
}