Validator
Validator is a user input validation library written in Swift.
๐ด If you're looking for the old Objective-C implementation (AJWValidator) visit the objc branch.
Features
- Validation rules
- Swift standard library type extensions
- UIKit element extensions
- Flexible validation error types
- An open protocol-oriented implementation
- Comprehensive test coverage
Installation
Install Validator with CocoaPods:
pod 'Validator'
Note - Embedded frameworks require a minimum deployment target of iOS 8.
Usage
Validator
can validate any Validatable
type using one or multiple ValidationRule
s. A validation operation returns a ValidationResult
which matches either .Valid
or .Invalid([ValidationErrorType])
, where ValidationErrorType
extends ErrorType
.
let rule = ValidationRulePattern(pattern: .EmailAddress, failureError: someValidationErrorType)
let result = "invalid@email,com".validate(rule: rule)
// Note: the above is equivalent to Validator.validate(input: "invalid@email,com", rule: rule)
switch result {
case .Valid: print("๐")
case .Invalid(let failures): print(failures.first?.message)
}
Validation Rules
Equality
Validates an Equatable
type is equal to another.
let staticEqualityRule = ValidationRuleEquality<String>(target: "hello", failureError: someValidationErrorType)
let dynamicEqualityRule = ValidationRuleEquality<String>(dynamicTarget: { return textField.text ?? "" }, failureError: someValidationErrorType)
Comparison
Validates a Comparable
type against a maximum and minimum.
let comparisonRule = ValidationRuleComparison<Float>(min: 5, max: 7, failureError: someValidationErrorType)
Length
Validates a String
length satisfies a minimum, maximum or range.
let minLengthRule = ValidationRuleLength(min: 5, failureError: someValidationErrorType)
let maxLengthRule = ValidationRuleLength(max: 5, failureError: someValidationErrorType)
let rangeLengthRule = ValidationRuleLength(min: 5, max: 10, failureError: someValidationErrorType)
Pattern
Validates a String
against a pattern. Validator provides some common patterns in the ValidationPattern
enum.
let emailRule = ValidationRulePattern(pattern: .EmailAddress, failureError: someValidationErrorType)
let digitRule = ValidationRulePattern(pattern: .ContainsDigit, failureError: someValidationErrorType)
let helloRule = ValidationRulePattern(pattern: ".*hello.*", failureError: someValidationErrorType)
Condition
Validates a Validatable
type with a custom condition.
let conditionRule = ValidationRuleCondition<[String]>(failureError: someValidationErrorType) { $0.contains("Hello") }
Create Your Own
Create your own validation rules by conforming to the ValidationRule
protocol:
protocol ValidationRule {
typealias InputType
func validateInput(input: InputType) -> Bool
var failureError: ValidationErrorType { get }
}
Example:
struct HappyRule {
typealias InputType = String
var failureError: ValidationError(message: "U mad?") }
func validateInput(input: String) -> Bool {
return input == "๐"
}
}
If your custom rule doesn't already exist in the library and you think it might be useful for other people, then it'd be great if you added it in with a pull request.
ValidationRuleSet
)
Multiple Validation Rules (Validation rules can be combined into a ValidationRuleSet
containing a collection of rules that validate a type.
var passwordRules = ValidationRuleSet<String>()
let minLengthRule = ValidationRuleLength(min: 5, failureError: someValidationErrorType)
passwordRules.addRule(minLengthRule)
let digitRule = ValidationRulePattern(pattern: .ContainsDigit, failureError: someValidationErrorType)
passwordRules.addRule(digitRule)
Validatable
Any type that conforms to the Validatable
protocol can be validated using the validate:
method.
// Validate with a single rule:
let result = "some string".validate(rule: aRule)
// Validate with a collection of rules:
let result = 42.validate(rules: aRuleSet)
Extend Types As Validatable
Extend the Validatable
protocol to make a new type validatable.
extension Thing : Validatable { }
Note: The implementation inside the protocol extension should mean that you don't need to implement anything yourself unless you need to validate multiple properties.
ValidationResult
The validate:
method returns a ValidationResult
enum. ValidationResult
can take one of two forms:
.Valid
: The input satisfies the validation rules..Invalid
: The input fails the validation rules. An.Invalid
result has an associated array of types conforming toValidationErrorType
.
You can combine two or more ValidationResult
s together with merge:
.
let result1 = ValidationResult.Invalid([someError])
let result2 = ValidationResult.Invalid([someError2])
let allResults = result1.merge(result2) // = ValidationResult.Invalid([someError1, someError2])
ValidationErrorType
The ValidationErrorType
extends ErrorType
and adds a message property for holding a validation error message. This means that they're compatible with Swift 2 error handling and flexible for defining your own.
struct User: Validatable {
let email: String
enum ValidationErrors: String, ValidationErrorType {
case EmailInvalid = "Email address is invalid"
var message { return self.rawValue }
}
func validate() -> ValidationResult {
let rule ValidationRulePattern(pattern: .EmailAddress, failureError: ValidationErrors.EmailInvalid)
return email.validate(rule: rule)
}
}
Validator also ships with a basic ValidationError
struct if you'd prefer to use that. It implements ValidationErrorType
:
public struct ValidationError: ValidationErrorType {
public let message: String
public init(message m: String) {
message = m
}
}
Validating UIKit Elements
UIKit elements that conform to ValidatableInterfaceElement
can have their input validated with the validate:
method.
let textField = UITextField()
textField.text = "I'm going to be validated"
let slider = UISlider()
slider.value = 0.3
// Validate with a single rule:
let result = textField.validate(rule: aRule)
// Validate with a collection of rules:
let result = slider.validate(rules: aRuleSet)
Validate On Input Change
A ValidatableInterfaceElement
can be configured to automatically validate when the input changes in 3 steps.
-
Attach a set of default rules:
let textField = UITextField() let rules = ValidationRuleSet<String>() rules.addRule(someRule) textField.validationRules = rules
-
Attach a closure to fire on input change:
textField.validationHandler = { result in switch result { case .Valid: textField.textColor = UIColor.blackColor() case .Invalid(let failureErrors): let messages = failureErrors.map { $0.message } print(messages) textField.textColor = UIColor.redColor() } }
-
Begin observation:
textField.validateOnInputChange(true)
Note - Use .validateOnInputChange(false)
to end observation.
Extend UI Elements As Validatable
Extend the ValidatableInterfaceElement
protocol to make an interface element validatable.
Example:
extension UITextField: ValidatableInterfaceElement {
typealias InputType = String
var inputValue: String { return text ?? "" }
func validateOnInputChange(validationEnabled: Bool) {
switch validationEnabled {
case true: addTarget(self, action: "validateInputChange:", forControlEvents: .EditingChanged)
case false: removeTarget(self, action: "validateInputChange:", forControlEvents: .EditingChanged)
}
}
@objc private func validateInputChange(sender: UITextField) {
sender.validate()
}
}
The implementation inside the protocol extension should mean that you should only need to implement:
- The
typealias
: the type of input to be validated (e.gString
forUITextField
). - The
inputValue
: the input value to be validated (e.g thetext
value forUITextField
). - The
validateOnInputChange:
method: to configure input-change observation.
Examples
There's an example project in this repository.
Contributing
Any contributions and suggestions are most welcome! Please ensure any new code is covered with unit tests, and that all existing tests pass. Please update the README with any new features. Thanks!
Contact
License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.