{"id":19809492,"url":"https://github.com/space-code/validator","last_synced_at":"2025-05-01T08:30:51.167Z","repository":{"id":196049587,"uuid":"693080863","full_name":"space-code/validator","owner":"space-code","description":"Validator is a framework written in Swift that provides functions that can be used to validate the contents of an input value.","archived":false,"fork":false,"pushed_at":"2024-01-10T17:05:45.000Z","size":313,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"dev","last_synced_at":"2024-10-04T20:45:26.700Z","etag":null,"topics":["form","swift","swiftui","validation"],"latest_commit_sha":null,"homepage":"","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/space-code.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-09-18T10:02:24.000Z","updated_at":"2024-06-18T10:29:34.000Z","dependencies_parsed_at":"2023-11-21T07:03:39.257Z","dependency_job_id":"783fcad9-5263-4a7f-a14c-f43054a2f3b8","html_url":"https://github.com/space-code/validator","commit_stats":{"total_commits":22,"total_committers":1,"mean_commits":22.0,"dds":0.0,"last_synced_commit":"93fd64941225edcbc846f53c0e740d0124ab8ff5"},"previous_names":["space-code/validator"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-code%2Fvalidator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-code%2Fvalidator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-code%2Fvalidator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/space-code%2Fvalidator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/space-code","download_url":"https://codeload.github.com/space-code/validator/tar.gz/refs/heads/dev","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224091954,"owners_count":17254152,"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":["form","swift","swiftui","validation"],"created_at":"2024-11-12T09:17:11.401Z","updated_at":"2025-05-01T08:30:51.157Z","avatar_url":"https://github.com/space-code.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Validator: xxxxx](https://raw.githubusercontent.com/space-code/validator/dev/Resources/validator.png)\n\n\u003ch1 align=\"center\" style=\"margin-top: 0px;\"\u003evalidator\u003c/h1\u003e\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://github.com/space-code/validator/blob/main/LICENSE\"\u003e\u003cimg alt=\"Licence\" src=\"https://img.shields.io/cocoapods/l/service-core.svg?style=flat\"\u003e\u003c/a\u003e \n\u003ca href=\"https://swiftpackageindex.com/space-code/validator\"\u003e\u003cimg alt=\"Swift Compatibility\" src=\"https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fspace-code%2Fvalidator%2Fbadge%3Ftype%3Dswift-versions\"/\u003e\u003c/a\u003e \n\u003ca href=\"https://swiftpackageindex.com/space-code/validator\"\u003e\u003cimg alt=\"Platform Compatibility\" src=\"https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fspace-code%2Fvalidator%2Fbadge%3Ftype%3Dplatforms\"/\u003e\u003c/a\u003e \n\u003ca href=\"https://github.com/space-code/validator\"\u003e\u003cimg alt=\"CI\" src=\"https://github.com/space-code/validator/actions/workflows/ci.yml/badge.svg?branch=main\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/apple/swift-package-manager\" alt=\"Validator on Swift Package Manager\" title=\"Validator on Swift Package Manager\"\u003e\u003cimg src=\"https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://codecov.io/gh/space-code/validator\" \u003e  \u003cimg src=\"https://codecov.io/gh/space-code/validator/graph/badge.svg?token=3B8FE96372\"/\u003e  \u003c/a\u003e\n\u003c/p\u003e\n\n## Description\nValidator is a framework written in Swift that provides functions that can be used to validate the contents of an input value.\n\n- [Usage](#usage)\n- [Validation Rules](#validation-rules)\n- [Custom Validation Rules](#custom-validation-rules)\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [Communication](#communication)\n- [Contributing](#contributing)\n- [Author](#author)\n- [License](#license)\n\n## Usage\n\nThe package contains two libraries: `ValidatorCore` encompasses all validation logic and predefined validators, while `ValidatorUI` implements extensions for integrating the validator into UI objects. It supports both `SwiftUI` and `UIKit`.\n\n### Basic usage\n\nIf you need to validate some data, you can use the `Validator` object for this purpose as follows:\n\n```swift\nimport ValidatorCore\n\nlet validator = Validator()\nlet result = validator.validate(input: \"text\", rule: LengthValidationRule(min: 4, error: \"error text\"))\n\nswitch result {\ncase .valid:\n    print(\"text is valid\")\ncase let .invalid(errors):\n    // handle validation errors\n    print(errors)\n}\n```\n\n### UIKit\n\nIf you want to validate a user's input data, you can import `ValidatorUI` and integrate validation logic into UI components. Your UI object must conform to `IUIValidatable` prototocol that requires to define an `inputValue` and `validateOnInputChange(_:)` method.\n\n`ValidatorUI` supports an extension for convenient integration of the validator into `UITextField` objects:\n\n```swift\nimport UIKit\nimport ValidatorUI\nimport ValidatorCore\n\nclass ViewController: UIViewController {\n\n    let textField: UITextField = UITextField()\n\n    override func viewDidLoad() {\n        super.viewDidLoad()\n        \n        /// Adds validation rule to the text field.\n        textField.add(rule: LengthValidationRule(max: 10, error: \"error text\"))\n        /// Enables automatic validation on input change.\n        textField.validateOnInputChange(isEnabled: true)\n        /// Handle the validation result.\n        textField.validationHandler = { result in\n            switch result {\n            case .valid:\n                print(\"text is valid\")\n            case let .invalid(errors):\n                print(errors)\n            }\n        }\n    }\n\n    /// Setup UITextField ...\n}\n```\n\n### SwiftUI\n\nIf you need to validate a single field, you can use the validation view extension and handle the validation result in a validation handler:\n\n```swift\nimport SwiftUI\nimport ValidatorUI\nimport ValidatorCore\n\nstruct ContentView: View {\n    @State private var text: String = \"\"\n    \n    private let validationRules: [any IValidationRule\u003cString\u003e] = [\n        LengthValidationRule(max: 10, error: \"Text error\")\n    ]\n    \n    var body: some View {\n        VStack {\n            TextField(\"Text\", text: $text)\n                .validation($text, rules: validationRules) { result in\n                    // Handle a validation result here\n                }\n        }\n    }\n}\n```\n\nYou can also use a view modifier where you can pass an error view:\n\n```swift\nimport SwiftUI\nimport ValidatorUI\nimport ValidatorCore\n\nstruct ContentView: View {\n    @State private var text: String = \"\"\n    \n    private let validationRules: [any IValidationRule\u003cString\u003e] = [\n        LengthValidationRule(max: 10, error: \"Text error\")\n    ]\n    \n    var body: some View {\n        VStack {\n            TextField(\"Text\", text: $text)\n                .validate(item: $text, rules: validationRules) { errors in\n                    Text(\"Text is bigger than 10 characters\")\n                }\n        }\n    }\n}\n```\n\n### SwiftUI Forms\n\n`ValidatorUI` supports form validation. If your screen contains a number of input fields and you want to handle validation results in one place, you can use a validation form manager as follows:\n\n```swift\nimport SwiftUI\nimport ValidatorUI\nimport ValidatorCore\n\nclass Form: ObservableObject {\n    @Published\n    var manager = FormFieldManager()\n\n    @FormField(rules: [LengthValidationRule(max: 20, error: \"The first name is very long\")])\n    var firstName: String = \"\"\n\n    @FormField(rules: [LengthValidationRule(min: 5, error: \"The last name is too short\")])\n    var lastName: String = \"\"\n    \n    lazy var firstNameValidationContainer = _firstName.validate(manager: manager)\n    lazy var lastNameValidationContainer = _lastName.validate(manager: manager)\n}\n\nstruct ContentView: View {\n    @ObservedObject private var form = Form()\n\n    var body: some View {\n        VStack {\n            TextField(\"First Name\", text: $form.firstName)\n                .validate(validationContainer: form.firstNameValidationContainer) { errors in\n                    Text(errors.map { $0.message }.joined(separator: \" \"))\n                }\n            TextField(\"Last Name\", text: $form.lastName)\n                .validate(validationContainer: form.lastNameValidationContainer) { errors in\n                    Text(errors.map { $0.message }.joined(separator: \" \"))\n                }\n            Button(action: { self.form.manager.validate() }, label: { Text(\"Validate\") })\n\n            Spacer()\n        }\n        .onReceive(\n            form.manager.$isValid,\n            perform: { value in\n                if value {\n                    print(\"The form's fields are valid\")\n                } else {\n                    print(\"The form's fields aren't valid\")\n                }\n            }\n        )\n    }\n}\n```\n\n## Validation Rules\n\n| **Validator**              | **Description**                                                                     |\n|----------------------------|-------------------------------------------------------------------------------------|\n| **LengthValidationRule**   | To validate whether a string is matching a specific length                          |\n| **NonEmptyValidationRule** | To validate whether a string is empty or blank                                      |\n| **PrefixValidationRule**   | To validate whether a string contains a prefix                                      |\n| **SuffixValidationRule**   | To validate whether a string contains a suffix                                      |\n| **RegexValidationRule**    | To validate if a pattern is matched                                                 |\n\n## Custom Validation Rules\n\nTo implement a custom validation rule, you can conform to the `IValidationRule` protocol, which requires defining a validation type and implementing validation logic. For example:\n\n```swift\n/// A non empty validation rule.\npublic struct NonEmptyValidationRule: IValidationRule {\n    // MARK: Types\n\n    public typealias Input = String\n\n    // MARK: Properties\n\n    /// The validation error.\n    public let error: IValidationError\n\n    // MARK: Initialization\n\n    public init(error: IValidationError) {\n        self.error = error\n    }\n\n    // MARK: IValidationRule\n\n    public func validate(input: String) -\u003e Bool {\n        !input.isEmpty\n    }\n}\n```\n\n## Requirements\n- iOS 16.0+ / macOS 13+ / tvOS 16.0+ / watchOS 9.0+\n- Xcode 14.0\n- Swift 5.7\n\n## Installation\n### Swift Package Manager\n\nThe [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but `validator` does support its use on supported platforms.\n\nOnce you have your Swift package set up, adding `validator` as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.\n\n```swift\ndependencies: [\n    .package(url: \"https://github.com/space-code/validator.git\", .upToNextMajor(from: \"1.1.0\"))\n]\n```\n\n## Communication\n- If you **found a bug**, open an issue.\n- If you **have a feature request**, open an issue.\n- If you **want to contribute**, submit a pull request.\n\n## Contributing\nBootstrapping development environment\n\n```\nmake bootstrap\n```\n\nPlease feel free to help out with this project! If you see something that could be made better or want a new feature, open up an issue or send a Pull Request!\n\n## Author\nNikita Vasilev, nv3212@gmail.com\n\n## License\nvalidator is available under the MIT license. See the LICENSE file for more info.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspace-code%2Fvalidator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspace-code%2Fvalidator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspace-code%2Fvalidator/lists"}