{"id":13467367,"url":"https://github.com/adamwaite/Validator","last_synced_at":"2025-03-26T02:31:24.307Z","repository":{"id":13662903,"uuid":"16356520","full_name":"adamwaite/Validator","owner":"adamwaite","description":"Drop in user input validation for your iOS apps.","archived":true,"fork":false,"pushed_at":"2020-06-12T14:59:04.000Z","size":74426,"stargazers_count":1420,"open_issues_count":15,"forks_count":218,"subscribers_count":32,"default_branch":"master","last_synced_at":"2024-10-29T21:53:40.672Z","etag":null,"topics":["ios","swift","validation","validation-library","validators"],"latest_commit_sha":null,"homepage":null,"language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/adamwaite.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-01-29T19:51:38.000Z","updated_at":"2024-10-22T12:48:40.000Z","dependencies_parsed_at":"2022-08-31T06:50:58.801Z","dependency_job_id":null,"html_url":"https://github.com/adamwaite/Validator","commit_stats":null,"previous_names":["adamwaite/ajwvalidator"],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adamwaite%2FValidator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adamwaite%2FValidator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adamwaite%2FValidator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/adamwaite%2FValidator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/adamwaite","download_url":"https://codeload.github.com/adamwaite/Validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245576529,"owners_count":20638125,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ios","swift","validation","validation-library","validators"],"created_at":"2024-07-31T15:00:55.467Z","updated_at":"2025-03-26T02:31:22.497Z","avatar_url":"https://github.com/adamwaite.png","language":"Swift","readme":"# Validator\n\nValidator is a user input validation library written in Swift. It's comprehensive, designed for extension, and leaves the UI up to you.\n\nHere's how you might validate an email address:\n\n```swift\nlet emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: validationError)\n\"invalid@email,com\".validate(emailRule) // -\u003e .invalid(validationError)\n```\n\n... or that a user is over the age of 18:\n\n```swift\nlet eighteenYearsAgo = Date().addingTimeInterval(-568024668)\nlet drinkingAgeRule = ValidationRuleComparison\u003cDate\u003e(min: eighteenYearsAgo, error: validationError)\nlet dateOfBirth = Date().addingTimeInterval(-662695446) // 21 years old\ndateOfBirth.validate(rule: rule) // -\u003e .valid\n```\n\n... or that a number is within a specified range:\n\n```swift\nlet numericRule = ValidationRuleComparison\u003cInt\u003e(min: 50, max: 100, error: validationError)\n42.validate(numericRule) // -\u003e .invalid(validationError)\n```\n\n.. or that a text field contains a valid Visa or American Express card number:\n\n```swift\nlet cardRule = ValidationRulePaymentCard(availableTypes: [.visa, .amex], error: validationError)\npaymentCardTextField.validate(cardRule) // -\u003e .valid or .invalid(validationError) depending on what's in paymentCardTextField\n```\n\n## Features\n\n- [x] Validation rules:\n  - [x] Required\n  - [x] Equality\n  - [x] Comparison\n  - [x] Length (min, max, range)\n  - [x] Pattern (email, password constraints and more...)\n  - [x] Contains\n  - [x] URL\n  - [x] Payment card (Luhn validated, accepted types)\n  - [x] Condition (quickly write your own)\n- [x] Swift standard library type extensions with one API (not just strings!)\n- [x] UIKit element extensions\n- [x] Open validation error types\n- [x] An open protocol-oriented implementation\n- [x] Comprehensive test coverage\n- [x] Comprehensive code documentation\n\n## Demo\n\n![demo-vid](resources/validator-example.mov.gif)\n\n## Installation\n\n### CocoaPods\n\n[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Validator.svg)](https://github.com/CocoaPods/CocoaPods) [![CocoaPods Compatible](https://img.shields.io/cocoapods/dt/Validator.svg)](https://github.com/CocoaPods/CocoaPods)\n\n`pod 'Validator'`\n\n### Carthage\n\n [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)\n\n`github \"adamwaite/Validator\"`\n\n## Usage\n\n`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])`.\n\n```swift\nlet rule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: validationError)\n\nlet result = \"invalid@email,com\".validate(rule: rule)\n// Note: the above is equivalent to Validator.validate(input: \"invalid@email,com\", rule: rule)\n\nswitch result {\ncase .valid: print(\"😀\")\ncase .invalid(let failures): print(failures.first?.message)\n}\n```\n\n### Validation Rules\n\n#### Required\n\nValidates a type exists (not-nil).\n\n```swift\nlet stringRequiredRule = ValidationRuleRequired\u003cString?\u003e(error: validationError)\n\nlet floatRequiredRule = ValidationRuleRequired\u003cFloat?\u003e(error: validationError)\n```\n\n*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)`.*\n\n#### Equality\n\nValidates an `Equatable` type is equal to another.\n\n```swift\nlet staticEqualityRule = ValidationRuleEquality\u003cString\u003e(target: \"hello\", error: validationError)\n\nlet dynamicEqualityRule = ValidationRuleEquality\u003cString\u003e(dynamicTarget: { return textField.text ?? \"\" }, error: validationError)\n```\n\n#### Comparison\n\nValidates a `Comparable` type against a maximum and minimum.\n\n```swift\nlet comparisonRule = ValidationRuleComparison\u003cFloat\u003e(min: 5, max: 7, error: validationError)\n```\n\n#### Length\n\nValidates a `String` length satisfies a minimum, maximum or range.\n\n```swift\nlet minLengthRule = ValidationRuleLength(min: 5, error: validationError)\n\nlet maxLengthRule = ValidationRuleLength(max: 5, error: validationError)\n\nlet rangeLengthRule = ValidationRuleLength(min: 5, max: 10, error: validationError)\n```\n\n#### Pattern\n\nValidates a `String` against a pattern.\n\n`ValidationRulePattern` can be initialised with a `String` pattern or a type conforming to `ValidationPattern`. Validator provides some common patterns in the Patterns directory.\n\n```swift\nlet emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: validationError)\n\nlet digitRule = ValidationRulePattern(pattern: ContainsNumberValidationPattern(), error: someValidationErrorType)\n\nlet helloRule = ValidationRulePattern(pattern: \".*hello.*\", error: validationError)\n```\n\n#### Contains\n\nValidates an `Equatable` type is within a predefined `SequenceType`'s elements (where the `Element` of the `SequenceType` matches the input type).\n\n```swift\nlet stringContainsRule = ValidationRuleContains\u003cString, [String]\u003e(sequence: [\"hello\", \"hi\", \"hey\"], error: validationError)\n\nlet rule = ValidationRuleContains\u003cInt, [Int]\u003e(sequence: [1, 2, 3], error: validationError)\n```\n\n#### URL\n\nValidates a `String` to see if it's a valid URL conforming to RFC 2396.\n\n```swift\nlet urlRule = ValidationRuleURL(error: validationError)\n```\n\n#### Payment Card\n\nValidates a `String` to see if it's a valid payment card number by firstly running it through the [Luhn check algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm), and secondly ensuring it follows the format of a number of payment card providers.\n\n```swift\npublic enum PaymentCardType: Int {\n    case amex, mastercard, visa, maestro, dinersClub, jcb, discover, unionPay\n    ///...\n```\n\nTo be validate against any card type (just the Luhn check):\n\n```swift\nlet anyCardRule = ValidationRulePaymentCard(error: validationError)\n```\n\nTo be validate against a set of accepted card types (e.g Visa, Mastercard and American Express in this example):\n\n```swift\nlet acceptedCardsRule = ValidationRulePaymentCard(acceptedTypes: [.visa, .mastercard, .amex], error: validationError)\n```\n\n#### Condition\n\nValidates a `Validatable` type with a custom condition.\n\n```swift\nlet conditionRule = ValidationRuleCondition\u003c[String]\u003e(error: validationError) { $0.contains(\"Hello\") }\n```\n\n#### Create Your Own\n\nCreate your own validation rules by conforming to the `ValidationRule` protocol:\n\n```swift\nprotocol ValidationRule {\n    typealias InputType\n    func validate(input: InputType) -\u003e Bool\n    var error: ValidationError { get }\n}\n```\n\nExample:\n\n```swift\nstruct HappyRule {\n    typealias InputType = String\n    var error: ValidationError\n    func validate(input: String) -\u003e Bool {\n        return input == \"😀\"\n    }\n}\n```\n\n\u003e 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](https://github.com/adamwaite/Validator/pulls).\n\n### Multiple Validation Rules (`ValidationRuleSet`)\n\nValidation rules can be combined into a `ValidationRuleSet` containing a collection of rules that validate a type.\n\n```swift\nvar passwordRules = ValidationRuleSet\u003cString\u003e()\n\nlet minLengthRule = ValidationRuleLength(min: 5, error: validationError)\npasswordRules.add(rule: minLengthRule)\n\nlet digitRule = ValidationRulePattern(pattern: .ContainsDigit, error: validationError)\npasswordRules.add(rule: digitRule)\n```\n\n### Validatable\n\nAny type that conforms to the `Validatable` protocol can be validated using the `validate:` method.\n\n```swift\n// Validate with a single rule:\n\nlet result = \"some string\".validate(rule: aRule)\n\n// Validate with a collection of rules:\n\nlet result = 42.validate(rules: aRuleSet)\n```\n\n#### Extend Types As Validatable\n\nExtend the `Validatable` protocol to make a new type validatable.\n\n`extension Thing : Validatable { }`\n\nNote: The implementation inside the protocol extension should mean that you don't need to implement anything yourself unless you need to validate multiple properties.\n\n### ValidationResult\n\nThe `validate:` method returns a `ValidationResult` enum. `ValidationResult` can take one of two forms:\n\n1. `.valid`: The input satisfies the validation rules.\n2. `.invalid`: The input fails the validation rules. An `.invalid` result has an associated array of types conforming to `ValidationError`.\n\n### Errors\n\nInitialize rules with any `ValidationError` to be passed with the result on a failed validation.\n\nExample:\n\n```swift\nstruct User: Validatable {\n\n    let email: String\n\n    enum ValidationErrors: String, ValidationError {\n        case emailInvalid = \"Email address is invalid\"\n        var message { return self.rawValue }\n    }\n\n    func validate() -\u003e ValidationResult {\n        let rule ValidationRulePattern(pattern: .emailAddress, error: ValidationErrors.emailInvalid)\n        return email.validate(rule: rule)\n    }\n}\n\n```\n\n### Validating UIKit Elements\n\nUIKit elements that conform to `ValidatableInterfaceElement` can have their input validated with the `validate:` method.\n\n```swift\nlet textField = UITextField()\ntextField.text = \"I'm going to be validated\"\n\nlet slider = UISlider()\nslider.value = 0.3\n\n// Validate with a single rule:\n\nlet result = textField.validate(rule: aRule)\n\n// Validate with a collection of rules:\n\nlet result = slider.validate(rules: aRuleSet)\n```\n\n#### Validate On Input Change\n\nA `ValidatableInterfaceElement` can be configured to automatically validate when the input changes in 3 steps.\n\n1. Attach a set of default rules:\n\n    ```swift\n    let textField = UITextField()\n    var rules = ValidationRuleSet\u003cString\u003e()\n    rules.add(rule: someRule)\n    textField.validationRules = rules\n    ```\n\n2. Attach a closure to fire on input change:\n\n    ```swift\n    textField.validationHandler = { result in\n\t  switch result {\n      case .valid:\n\t\t    print(\"valid!\")\n      case .invalid(let failureErrors):\n\t\t    let messages = failureErrors.map { $0.message }\n        print(\"invalid!\", messages)\n      }\n    }\n    ```\n\n3. Begin observation:\n\n    ```swift\n    textField.validateOnInputChange(enabled: true)\n    ```\n\nNote - Use `.validateOnInputChange(enabled: false)` to end observation.\n\n#### Extend UI Elements As Validatable\n\nExtend the `ValidatableInterfaceElement` protocol to make an interface element validatable.\n\nExample:\n\n```swift\nextension UITextField: ValidatableInterfaceElement {\n\n    typealias InputType = String\n\n    var inputValue: String { return text ?? \"\" }\n\n    func validateOnInputChange(enabled: Bool) {\n        switch validationEnabled {\n        case true: addTarget(self, action: #selector(validateInputChange), forControlEvents: .editingChanged)\n        case false: removeTarget(self, action: #selector(validateInputChange), forControlEvents: .editingChanged)\n        }\n    }\n\n    @objc private func validateInputChange(_ sender: UITextField) {\n        sender.validate()\n    }\n\n}\n```\n\nThe implementation inside the protocol extension should mean that you should only need to implement:\n\n1.  The `typealias`: the type of input to be validated (e.g `String` for `UITextField`).\n2.  The `inputValue`: the input value to be validated (e.g the `text` value for `UITextField`).\n3.  The `validateOnInputChange:` method: to configure input-change observation.\n\n## Examples\n\nThere's an example project in this repository.\n\n## Contributing\n\nAny 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!\n\n## Contact\n\n[@adamwaite](http://twitter.com/adamwaite)\n\n## License\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n","funding_links":[],"categories":["Libs","Validation [🔝](#readme)"],"sub_categories":["Validation"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fadamwaite%2FValidator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fadamwaite%2FValidator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fadamwaite%2FValidator/lists"}