Declarative data validation framework, written in Swift

Overview

Peppermint badge-version

badge-build-macos badge-build-linux badge-codecov badge-docs badge-license badge-twitter

  1. Introduction
  2. Requirements
  3. Installation
  4. Usage Examples
  5. Contribute
  6. Meta

Introduction

let constraint = TypeConstraint<Account, Account.Error> {
    KeyPathConstraint(\.username) {
        BlockConstraint {
            $0.count >= 5
        } errorBuilder: {
            .username
        }
    }
    KeyPathConstraint(\.password) {
        GroupConstraint(.all) {
            PredicateConstraint {
                .characterSet(.lowercaseLetters, mode: .inclusive)
            } errorBuilder: {
                .password(.missingLowercase)
            }
            PredicateConstraint{
                .characterSet(.uppercaseLetters, mode: .inclusive)
            } errorBuilder: {
                .password(.missingUppercase)
            }
            PredicateConstraint {
                .characterSet(.decimalDigits, mode: .inclusive)
            } errorBuilder: {
                .password(.missingDigits)
            }
            PredicateConstraint {
                .characterSet(CharacterSet(charactersIn: "!?@#$%^&*()|\\/<>,.~`_+-="), mode: .inclusive)
            } errorBuilder: {
                .password(.missingSpecialChars)
            }
            PredicateConstraint {
                .length(min: 8)
            }  errorBuilder: {
                .password(.tooShort)
            }
        }
    }
    BlockConstraint {
        $0.password == $0.passwordConfirmation
    } errorBuilder: {
        .password(.confirmationMismatch)
    }
    KeyPathConstraint(\.email) {
        PredicateConstraint(.email, error: .email)
    }
    KeyPathConstraint(\.age) {
        PredicateConstraint(.range(min: 14), error: .underAge)
    }
    KeyPathConstraint(\.website) {
        PredicateConstraint(.url, error: .website)
            .optional()
    }
}

let result = constraint.evaluate(with: account)
switch result {
case .success:
    handleSuccess()
case .failure(let summary):
    handleErrors(summary.errors)
}

Peppermint is a declarative and lightweight data validation framework.

At the core of it, there are 2 principles:

  • Empower composition.
  • Embrace standard library.

Every project is unique in it's own challenges and it's great when we can focus on solving them instead of spending our time on boilerplate tasks.

With this idea in mind, the framework follows the Protocol Oriented Programming paradigm and was designed from a small set of protocols and structures that can easily be composed to fit your project needs. Thus, you can think of Peppermint as an adjustable wrench more than a Swiss knife.

Since validation can take place at many levels, Peppermint is available on iOS, macOS, tvOS, watchOS and native Swift projects, such as server-side apps.

Requirements

  • Swift 4.2+
  • iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.1+

Installation

Peppermint is available only through Swift Package Manager.

Swift Package Manager

You can add Peppermint to your project in Xcode by going to File > Swift Packages > Add Package Dependency.

Or, if you want to use it as a dependency to your own package, you can add it to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/nsagora/peppermint", majorVersion: 1),
    ]
)

Usage example

For a comprehensive list of examples try out the Examples.playground:

  1. Download the repository locally on your machine
  2. Open the project in Xcode
  3. Select the Examples playground from the Project navigator

The Peppermint framework is compact and offers you the foundation you need to build data validation around your project needs. In addition, it includes a set of common validation predicates and constraints that most projects can benefit off.

Predicates

The Predicate represents the core protocol and has the role to evaluate if an input matches on a given validation condition.

At the core of Peppermint there are the following two predicates, which allows you to compose predicates specific to the project needs:

BlockPredicate
let predicate = BlockPredicate<String> { $0.characters.count > 2 }
predicate.evaluate(with: "a") // returns false
predicate.evaluate(with: "abc") // returns true
RegexPredicate
let predicate = RegexPredicate(expression: "^[a-z]$")
predicate.evaluate(with: "a") // returns true
predicate.evaluate(with: "5") // returns false
predicate.evaluate(with: "ab") // returns false

In addition, the framework offers a set of common validation predicates that your project can benefit of:

EmailPredicate
let predicate = EmailPredicate()
predicate.evaluate(with: "hello@") // returns false
predicate.evaluate(with: "[email protected]") // returns true
predicate.evaluate(with: "hΓ©[email protected]") // returns true
URLPredicate
let predicate = URLPredicate()
predicate.evaluate(with: "http://www.url.com") // returns true
predicate.evaluate(with: "http:\\www.url.com") // returns false
RangePredicate
let predicate = let range = RangePredicate(10...20)
predicate.evaluate(with: 15) // returns true
predicate.evaluate(with: 21) // returns false
LengthPredicate
let predicate = LengthPredicate<String>(min: 5)
predicate.evaluate(with: "abcde")   // returns true
predicate.evaluate(with: "abcd")    // returns false

On top of that, developers can build more advanced or complex predicates by extending the Predicate protocol, and/ or by composing or decorating the existing predicates:

Custom Predicate
public struct CustomPredicate: Predicate {

    public typealias InputType = String

    private let custom: String

    public init(custom: String) {
        self.custom = custom
    }

    public func evaluate(with input: String) -> Bool {
        return input == custom
    }
}

let predicate = CustomPredicate(custom: "alphabet")
predicate.evaluate(with: "alp") // returns false
predicate.evaluate(with: "alpha") // returns false
predicate.evaluate(with: "alphabet") // returns true

Constraints

Predicate Constraint

A PredicateConstraint represents a data type that links a Predicate to an Error, in order to provide useful feedback for the end users.

PredicateConstraint
let constraint = PredicateConstraint<String, MyError>(.email, error: .invalid)

let result = constraint.evaluate(with: "[email protected]")
switch result {
case .valid:
    print("Hi there πŸ‘‹!")
case .invalid(let summary):
    print("Oh, I was expecting a valid email address!")
}  // prints "Hi there πŸ‘‹!"
enum MyError: Error {
    case invalid
}

Block Constraint

A BlockConstraint represents a data type that links a custom validation closure to an Error that describes why the evaluation has failed. It's a shortcut of a PredicateConstraint that is initialised with a BlockPredicate.

BlockConstraint
let constraint = BlockConstraint<Int, MyError> {
    $0 % 2 == 0
} errorBuilder: {
    .magicNumber
}

constraint.evaluate(with: 3)
enum Failure: MyError {
    case magicNumber
}

Group Constraint

A GroupConstraint represents a composition of constraints that allows the evaluation to be made on:

  • all constraints
  • or any of the constraints

To provide context, a GroupConstraint allows us to constraint a piece of data as being required and also as being a valid email.

GroupConstraintAn example of a registration form, whereby users are prompted to enter a strong password. This process typically entails some form of validation, but the logic itself is often unstructured and spread out through a view controller.

Peppermint seeks instead to consolidate, standardise, and make explicit the logic that is being used to validate user input. To this end, the below example demonstrates construction of a full GroupConstraint object that can be used to enforce requirements on the user's password data:

var passwordConstraint = GroupConstraint<String, Form.Password>(.all) {
    PredicateConstraint {
        .characterSet(.lowercaseLetters, mode: .loose)
    } errorBuilder: {
        .missingLowercase
    }
    PredicateConstraint{
        .characterSet(.uppercaseLetters, mode: .loose)
    } errorBuilder: {
        .missingUppercase
    }
    PredicateConstraint {
        .characterSet(.decimalDigits, mode: .loose)
    } errorBuilder: {
        .missingDigits
    }
    PredicateConstraint {
        .characterSet(CharacterSet(charactersIn: "!?@#$%^&*()|\\/<>,.~`_+-="), mode: .loose)
    } errorBuilder: {
        .missingSpecialChars
    }
    PredicateConstraint {
        .length(min: 8)
    }  errorBuilder: {
        .minLength(8)
    }
}

let password = "3nGuard!"
let result = passwordConstraint.evaluate(with: password)

switch result {
case .success:
    print("Wow, that's a πŸ’ͺ password!")
case .failure(let summary):
    print(summary.errors.map({$0.localizedDescription}))
} // prints "Wow, that's a πŸ’ͺ password!"

From above, we see that once we've constructed the passwordConstraint, we're simply calling evaluate(with:) to get our evaluation Result. This contains a Summary that can be handled as we please.

Contribute

We would love you for the contribution to Peppermint, check the LICENSE file for more info.

Meta

This project is developed and maintained by the members of iOS NSAgora, the community of iOS Developers of IaΘ™i, Romania.

Distributed under the MIT license. See LICENSE for more information.

[https://github.com/nsagora/peppermint]

You might also like...
Imagine Engine - a fast, high performance Swift 2D game engine for Apple's platforms
Imagine Engine - a fast, high performance Swift 2D game engine for Apple's platforms

Welcome to Imagine Engine, an ongoing project that aims to create a fast, high performance Swift 2D game engine for Apple's platforms that is also a j

Sage is a cross-platform chess library for Swift.
Sage is a cross-platform chess library for Swift.

Sage is not a chess engine; it's a move generator. Hexe, on the other hand, is able to both generate moves and evaluate them.

🐦 Flappy Bird reincarnation [Swift 5.3, GameplayKit, SpriteKit, iOS 12].
🐦 Flappy Bird reincarnation [Swift 5.3, GameplayKit, SpriteKit, iOS 12].

🐦 Flappy Bird reincarnation [Swift 5.3, GameplayKit, SpriteKit, iOS 12].

A game engine built with SDL and Swift.

Lark A game engine made with Swift and SDL. This is a pre-alpha work-in-progress. Don't try to use this unless you really know what you're doing. I ba

A Swift package for Raylib. Builds Raylib from source so no need to fiddle with libraries.
A Swift package for Raylib. Builds Raylib from source so no need to fiddle with libraries.

A Swift package for Raylib. Builds Raylib from source so no need to fiddle with libraries. Just add as a dependency in you game package and go!

2048 for Swift

swift-2048 A working port of iOS-2048 to Apple's new Swift language. Like the original Objective-C version, swift-2048 does not rely upon SpriteKit. S

swift implementation of flappy bird. More at fullstackedu.com
swift implementation of flappy bird. More at fullstackedu.com

FlappySwift An implementation of Flappy Bird in Swift for iOS 8. Notes We're launching a course Game Programming with Swift If you are interested in e

iOS Swift Game - Push SpriteKit to the limit
iOS Swift Game - Push SpriteKit to the limit

iOS Swift Project - Legend Wings - EverWing's Mini Clone EverWing is a popular action game. Survive as much you can, earn gold, and upgrade/purchase n

A project introducing you to Swift

πŸ“± My first Memory πŸ€” πŸ’­ An introduction to iOS development with Swift. A memory game implementation fetching images from Instagram. This project aims

Comments
  • Bump excon from 0.70.0 to 0.71.1

    Bump excon from 0.70.0 to 0.71.1

    Bumps excon from 0.70.0 to 0.71.1.

    Changelog

    Sourced from excon's changelog.

    0.71.1 2019-12-18

    fix frozen chunks through dup prior to binary_encode

    0.71.0 2019-12-12

    fix for leftover data with interrupted persistent connections

    Commits
    • beb02b4 v0.71.1
    • ac85f68 Merge pull request #711 from unasuke/frozen_string_literal
    • 6609703 Use String#dup in Excon::Utils#binary_encode for frozen string
    • d498014 Add ruby-head to travis build matrix as allow_failure
    • 1149d44 v0.71.0
    • ccb57d7 fix for leftover data with interrupted persistent connections
    • See full diff in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot ignore this [patch|minor|major] version will close this PR and stop Dependabot creating any more for this minor/major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Introduce the concept of modifier

    Introduce the concept of modifier

    Inspired from SwiftUI,a modifier is a method on a constraint that returns a new constraint by decorating the caller with more functionality.

    For example, one may call the .optional() modifier to return an OptionalConstraint.

    The purpose is to simplify the API syntax.

    enhancement 
    opened by alexcristea 0
  • Add support for DocC

    Add support for DocC

    Apple introduced DocC at WWDC21. It is a documentation compiler which allows framework and package authors to write and publish reach and interactive documentation for their clients of their software.

    enhancement 
    opened by alexcristea 0
  • Define a MR template and checklist

    Define a MR template and checklist

    Create an MR template that contains a checklist of activities to perform before submitting the MR. This checklist should include like tests passing, every target builds, pod lint is successful, etc.

    enhancement help wanted 
    opened by alexcristea 0
Releases(1.2.0)
Owner
iOS NSAgora
iOS NSAgora
Swift-WordleSolver - Solve and analyze Wordle games. Command-line tool written in Swift

Swift-WordleSolver - Solve and analyze Wordle games. Command-line tool written in Swift

Tobi Schweiger 0 Jan 26, 2022
A simple Chess game for iOS, written in Swift

Swift Chess This is a simple chess game for iPhone and iPad, designed for novice players. It features a very simple AI that plays much like a beginner

Nick Lockwood 135 Jan 6, 2023
Simple memory game written in Swift 4 using VIPER Architecture.

Viper Memory Game Simple memory game written in Swift 4.2 using VIPER Architecture. The Memory Game is a deck of cards where the user needs to find ma

Mati 23 Jun 6, 2022
A command line version of the popular Wordle game, written in Swift

WordleCLI A command line version of the popular game Wordle. For the original game, see: https://www.powerlanguage.co.uk/wordle/ Usage $ swift run Wel

Eneko Alonso 2 Jan 18, 2022
Mergel - a match-and-merge game written in Swift, using SpriteKit

Mergel is a match-and-merge game written in Swift, using SpriteKit. It was created for the purpose of having some fun with SpriteKit and learning the Swift language.

Josh McKee 9 Nov 6, 2022
ShogibanKit is a framework (not yet) for implementing complex Japanese Chess (Shogii) in Swift. No UI, nor AI.

ShogibanKit Framework Shogi, or Japanese Chess, is based on very complex rules, and it is hard to implement all basic rules. This ShogibanKit aims to

Kaz Yoshikawa 62 Jul 16, 2022
Swift framework for working with Tiled assets in SpriteKit

SKTiled is a framework for integrating Tiled assets with Apple's SpriteKit, built from the ground up with Swift. This project began life as an exercis

Michael Fessenden 235 Dec 20, 2022
Swift framework for loading various 3d models in SceneKit

AssetImportKit AssetImportKit is a cross platform library (macOS, iOS) that coverts the files supported by Assimp to SceneKit scenes. Features AssetIm

eugene 74 Nov 30, 2022
3D Shoot'em Up written with OpenGL ES 1.1/2.0 running on iOS, Android, Windows and MacOS X.

SHMUP This is the source code of "SHMUP" a 3D Shoot 'em up that I wrote in 2009. It is very inspired of Treasure Ikaruga, the engine runs on iOS, Andr

Fabien 242 Dec 16, 2022
A snake engine written in SpriteKit for all Apple devices.

A snake engine written in SpriteKit for all Apple devices. ⭐ Features Fully tested engine functionality. Framework based, super easy to integrate in d

Chris Jimenez 59 Dec 13, 2022