Validator
Validator is a user input validation library written in Swift. It's comprehensive, designed for extension, and leaves the UI up to you.
Here's how you might validate an email address:
... or that a user is over the age of 18:
... or that a number is within a specified range:
.. or that a text field contains a valid Visa or American Express card number:
Features
- [x] Validation rules:
- [x] Required
- [x] Equality
- [x] Comparison
- [x] Length (min, max, range)
- [x] Pattern (email, password constraints and more...)
- [x] Contains
- [x] URL
- [x] Payment card (Luhn validated, accepted types)
- [x] Condition (quickly write your own)
- [x] Swift standard library type extensions with one API (not just strings!)
- [x] UIKit element extensions
- [x] Open validation error types
- [x] An open protocol-oriented implementation
- [x] Comprehensive test coverage
- [x] Comprehensive code documentation
Demo
Installation
CocoaPods
pod 'Validator'
Carthage
github "adamwaite/Validator"
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([Error])
.
Validation Rules
Required
Validates a type exists (not-nil).
Note - You can't use validate
on an optional Validatable
type (e.g. myString?.validate(aRule...)
because the optional chaining mechanism will bypass the call. "thing".validate(rule: aRule...)
is fine. To validate an optional for required in this way use: Validator.validate(input: anOptional, rule: aRule)
.
Equality
Validates an Equatable
type is equal to another.
Comparison
Validates a Comparable
type against a maximum and minimum.
Length
Validates a String
length satisfies a minimum, maximum or range.
Pattern
Validates a String
against a pattern.
ValidationRulePattern
can be initialised with a String
pattern or a type conforming to ValidationPattern
. Validator provides some common patterns in the Patterns directory.
Contains
Validates an Equatable
type is within a predefined SequenceType
's elements (where the Element
of the SequenceType
matches the input type).
URL
Validates a String
to see if it's a valid URL conforming to RFC 2396.
Payment Card
Validates a String
to see if it's a valid payment card number by firstly running it through the Luhn check algorithm, and secondly ensuring it follows the format of a number of payment card providers.
To be validate against any card type (just the Luhn check):
To be validate against a set of accepted card types (e.g Visa, Mastercard and American Express in this example):
Condition
Validates a Validatable
type with a custom condition.
Create Your Own
Create your own validation rules by conforming to the ValidationRule
protocol:
Example:
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.
Multiple Validation Rules (ValidationRuleSet
)
Validation rules can be combined into a ValidationRuleSet
containing a collection of rules that validate a type.
Validatable
Any type that conforms to the Validatable
protocol can be validated using the validate:
method.
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 toValidationError
.
Errors
Initialize rules with any ValidationError
to be passed with the result on a failed validation.
Example:
Validating UIKit Elements
UIKit elements that conform to ValidatableInterfaceElement
can have their input validated with the validate:
method.
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:
-
Attach a closure to fire on input change:
-
Begin observation:
Note - Use .validateOnInputChange(enabled: false)
to end observation.
Extend UI Elements As Validatable
Extend the ValidatableInterfaceElement
protocol to make an interface element validatable.
Example:
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.