Git Product home page Git Product logo

validatedpropertykit's Introduction

ValidatedPropertyKit Logo

Swift 5.1 Version Platform
Carthage Compatible SPM Documentation Twitter


ValidatedPropertyKit enables you to easily validate your properties
with the power of Property Wrappers.


struct User {
    
    @Validated(.nonEmpty)
    var username: String?
    
    @Validated(.isEmail)
    var email: String?
    
    @Validated(.range(8...))
    var password: String?
    
    @Validated(.greaterOrEqual(1))
    var friends: Int?
    
    @Validated(.isURL && .hasPrefix("https"))
    var avatarURL: String?
    
}

Features

  • Easily validate your properties ๐Ÿ‘ฎ
  • Predefined validations ๐Ÿšฆ
  • Logical Operators to combine validations ๐Ÿ”—
  • Customization and configuration to your needs ๐Ÿ’ช

Installation

โš ๏ธ ValidatedPropertyKit can currently only be used with Xcode 11 Beta and Swift 5.1.

CocoaPods

ValidatedPropertyKit is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'ValidatedPropertyKit'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

To integrate ValidatedPropertyKit into your Xcode project using Carthage, specify it in your Cartfile:

github "SvenTiigi/ValidatedPropertyKit"

Run carthage update to build the framework and drag the built ValidatedPropertyKit.framework into your Xcode project.

On your application targetsโ€™ โ€œBuild Phasesโ€ settings tab, click the โ€œ+โ€ icon and choose โ€œNew Run Script Phaseโ€ and add the Framework path as mentioned in Carthage Getting started Step 4, 5 and 6

Swift Package Manager

To integrate using Apple's Swift Package Manager, add the following as a dependency to your Package.swift:

dependencies: [
    .package(url: "https://github.com/SvenTiigi/ValidatedPropertyKit.git", from: "1.0.0")
]

Or navigate to your Xcode project then select Swift Packages, click the โ€œ+โ€ icon and search for ValidatedPropertyKit.

Xcode SPM

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate ValidatedPropertyKit into your project manually. Simply drag the Sources Folder into your Xcode project.

Usage

Validated ๐Ÿ‘ฎโ€โ™‚๏ธ

The @Validated attribute allows you to specify a validation along to the declaration of your property.

It is important to say that the @Validated attribute can only be applied to mutable Optional types as a validation can either succeed or fail.

@Validated(.nonEmpty)
var username: String?

username = "Mr.Robot"
print(username) // "Mr.Robot"

username = ""
print(username) // nil

Validation ๐Ÿšฆ

Every @Validated attribute must be initialized with a Validation which simply takes a (Value) -> Bool closure.

@Validated(.init { value in
    value.first == "A"
})
var status: String?

โ˜๏ธ Check out the Predefined Validations section to get an overview of the many predefined validations.

Additionally, you can extend the Validation struct via conditional conformance to easily declare your own Validations.

extension Validation where Value == Int {

    /// Will validate if the Integer is the meaning of life
    static var isMeaningOfLife: Validation {
        return .init { value in
            return value == 42
        }
    }

}

And apply them to your validated property.

@Validated(.isMeaningOfLife)
var number: Int?

Restore โ†ฉ๏ธ

Each property that is declared with the @Validated attribute can make use of the restore() function from the Validated Property Wrapper itself via the $ notation prefix.

When invoking $property.restore() the value will get restored to the last successful validated value.

@Validated(.nonEmpty)
var username: String?

username = "Mr.Robot"
print(username) // "Mr.Robot"

username = ""
print(username) // nil

// Restore to last successful validated value
$username.restore()
print(username) // "Mr.Robot"

isValid โœ…

As the aforementioned restore() function you can also access the isValid Bool value property to check if the current value is valid.

@Validated(.nonEmpty)
var username: String?

username = "Mr.Robot"
print($username.isValid) // true

username = ""
print($username.isValid) // false

Validation Operators ๐Ÿ”—

Validation Operators allowing you to combine multiple Validations like you would do with Bool values.

// Logical AND
@Validated(.isURL && .hasPrefix("https"))
var avatarURL: String?

// Logical OR
@Validated(.hasPrefix("Mr.") || .hasPrefix("Mrs."))
var name: String?

// Logical NOT
@Validated(!.contains("Android", options: .caseInsensitive))
var favoriteOperatingSystem: String?

Predefined Validations

The ValidatedPropertyKit comes with many predefined common validations which you can make use of in order to specify a Validation for your validated property.

KeyPath

The keyPath validation will allow you to specify a validation for a given KeyPath of the attributed property.

@Validated(.keyPath(\.isEnabled, .equals(true)))
var button: UIButton?

Strings

A String property can be validated in many ways like contains, hasPrefix and even RegularExpressions.

@Validated(.contains("Mr.Robot"))
var string: String?

@Validated(.hasPrefix("Mr."))
var string: String?

@Validated(.hasSuffix("OS"))
var string: String?

@Validated(.regularExpression("[0-9]+$"))
var string: String?

@Validated(.isLowercased)
var string: String?

@Validated(.isUppercased)
var string: String?

@Validated(.isEmail)
var string: String?

@Validated(.isURL)
var string: String?

@Validated(.isNumeric)
var string: String?

Equatable

A Equatable type can be validated against a specified value.

@Validated(.equals(42))
var number: Int?

Sequence

A property of type Sequence can be validated via the contains or startsWith validation.

@Validated(.contains("Mr.Robot", "Elliot"))
var sequence: [String]?

@Validated(.startsWith("First Entry"))
var sequence: [String]?

Collection

Every Collection type offers the nonEmpty validation and the range validation where you can easily declare the valid capacity.

@Validated(.nonEmpty)
var collection: [String]?

@Validated(.range(1...10))
var collection: [String]?

Comparable

A Comparable type can be validated with all common comparable operators.

@Validated(.less(50))
var comparable: Int?

@Validated(.lessOrEqual(50))
var comparable: Int?

@Validated(.greater(50))
var comparable: Int?

@Validated(.greaterOrEqual(50))
var comparable: Int?

Contributing

Contributions are very welcome ๐Ÿ™Œ

License

ValidatedPropertyKit
Copyright (c) 2019 Sven Tiigi [email protected]

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.

validatedpropertykit's People

Contributors

sventiigi avatar

Stargazers

Rogerio de Paula Assis avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.