Popularity
6.7
Growing
Activity
0.6
Growing
968
18
44

Programming language: Swift
License: MIT License
Tags: UI     Form & Settings    
Latest version: v0.0.4

ValidatedPropertyKit alternatives and similar libraries

Based on the "Form & Settings" category.
Alternatively, view ValidatedPropertyKit alternatives based on common mentions on social networks and blogs.

Do you think we are missing an alternative of ValidatedPropertyKit or a related project?

Add another 'Form & Settings' Library

README

ValidatedPropertyKit enables you to easily validate your propertieswith 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

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

Installation

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: "0.0.3")
]

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

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 will be initialized with a closure.

@Validated(.init { value in
   value.isEmpty ? .failure("String is empty") : .success(())
})
var username: 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
            value == 42 ? .success(()) : .failure("\(value) isn't the meaning of life")
        }
    }

}

And apply them to your validated property.

@Validated(.isMeaningOfLife)
var number: Int?

Error Handling ๐Ÿ•ต๏ธโ€โ™‚๏ธ

Each property that is declared with the @Validated attribute can make use of advanced functions and properties from the Validated Property Wrapper itself via the _ notation prefix.

Beside doing a simple nil check on your @Validated property to ensure if the value is valid or not you can access the validatedValue or validationError property to retrieve the ValidationError or the valid value.

@Validated(.nonEmpty)
var username: String?

// Switch on `validatedValue`
switch _username.validatedValue {
case .success(let value):
    // Value is valid โœ…
    break
case .failure(let validationError):
    // Value is invalid โ›”๏ธ
    break
}

// Or unwrap the `validationError`
if let validationError = _username.validationError {
    // Value is invalid โ›”๏ธ
} else {
    // Value is valid โœ…
}

Restore โ†ฉ๏ธ

Additionally, you can restore your @Validated property 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?

Featured on

Contributing

Contributions are very welcome ๐Ÿ™Œ

License

ValidatedPropertyKit
Copyright (c) 2020 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.


*Note that all licence references and agreements mentioned in the ValidatedPropertyKit README section above are relevant to that project's source code only.