ValidatedPropertyKit

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

ValidatedPropertyKit

struct User {
    
    @Validated(.nonEmpty)
    var username: String?
    
    @Validated(.isEmail)
    var email: String?
    
    @Validated(.range(8...))
    var password: String?
    
    @Validated(.greaterOrEqual(13))
    var age: Int?
    
    @Validated(.isURL && .hasSuffix("jpg"))
    var avatarURL: String?
    
    @Validated(!.contains("Android", options: .caseInsensitive))
    var favoriteOperatingSystem: String?
    
    @Validated(.init { $0.first == "+" })
    var phoneNumber: String?
    
}

Features

  • [x] Easily validate your properties ?
  • [x] Predefined validations ?
  • [x] Logical Operators to combine validations ?
  • [x] 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 == "+"
})
var phoneNumber: 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 && .hasSuffix("jpg"))
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?

GitHub