All Projects → adamwaite → Validator

adamwaite / Validator

Licence: mit
Drop in user input validation for your iOS apps.

Programming Languages

swift
15916 projects
ruby
36898 projects - #4 most used programming language
objective c
16641 projects - #2 most used programming language

Projects that are alternatives of or similar to Validator

Password Validator
Validates password according to flexible and intuitive specification
Stars: ✭ 224 (-84.49%)
Mutual labels:  validation, validation-library
Easyvalidation
✔️ A text and input validation library in Kotlin for Android
Stars: ✭ 328 (-77.29%)
Mutual labels:  validation, validation-library
valify
Validates data in JavaScript in a very simple way
Stars: ✭ 13 (-99.1%)
Mutual labels:  validation, validation-library
Deep Waters
🔥Deep Waters is an easy-to-compose functional validation system for javascript developers 🔥
Stars: ✭ 188 (-86.98%)
Mutual labels:  validation, validation-library
Validator Collection
Python library of 60+ commonly-used validator functions
Stars: ✭ 91 (-93.7%)
Mutual labels:  validation, validation-library
Php Validate
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。
Stars: ✭ 225 (-84.42%)
Mutual labels:  validation, validation-library
Valiktor
Valiktor is a type-safe, powerful and extensible fluent DSL to validate objects in Kotlin
Stars: ✭ 267 (-81.51%)
Mutual labels:  validation, validation-library
Validot
Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, structs, nested members, collections, nullables, plus any relation or combination of them. It also supports translations, custom logic extensions with tests, and DI containers.
Stars: ✭ 198 (-86.29%)
Mutual labels:  validation, validation-library
Laravel Vue Validator
Simple package to display error in vue from laravel validation
Stars: ✭ 32 (-97.78%)
Mutual labels:  validation, validation-library
Govalidator
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
Stars: ✭ 5,163 (+257.55%)
Mutual labels:  validation, validation-library
Typescript Runtime Type Benchmarks
Benchmark Comparison of Packages with Runtime Validation and TypeScript Support
Stars: ✭ 119 (-91.76%)
Mutual labels:  validation, validation-library
Fluidvalidator
General purpose validation system for objects, nested objects, enumerables written in Swift
Stars: ✭ 89 (-93.84%)
Mutual labels:  validation, validation-library
thai-citizen-id-validator
🦉 Validate Thai Citizen ID with 0 dependencies 🇹🇭
Stars: ✭ 35 (-97.58%)
Mutual labels:  validation, validation-library
Validator Docs
Validação de CPF, CNPJ, CNH, NIS, Título Eleitoral e Cartão Nacional de Saúde com Laravel.
Stars: ✭ 334 (-76.87%)
Mutual labels:  validation, validation-library
Lcformvalidation
Javascript based form validation library, third party library / framework agnostic.
Stars: ✭ 58 (-95.98%)
Mutual labels:  validation, validation-library
Vee Validate
✅ Form Validation for Vue.js
Stars: ✭ 8,820 (+510.8%)
Mutual labels:  validation, validation-library
Filetype
Fast, dependency-free, small Go package to infer the binary file type based on the magic numbers signature
Stars: ✭ 1,278 (-11.5%)
Mutual labels:  validation
Graphql Go Tools
Tools to write high performance GraphQL applications using Go/Golang.
Stars: ✭ 96 (-93.35%)
Mutual labels:  validation
Vest
Vest ✅ Declarative validations framework
Stars: ✭ 1,271 (-11.98%)
Mutual labels:  validation-library
React Native Merlin
🧙 Simple web-like forms in react native.
Stars: ✭ 83 (-94.25%)
Mutual labels:  validation

Validator

Validator is a user input validation library written in Swift. It's comprehensive, designed for extension, and leaves the UI up to you.

Here's how you might validate an email address:

let emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: validationError)
"invalid@email,com".validate(emailRule) // -> .invalid(validationError)

... or that a user is over the age of 18:

let eighteenYearsAgo = Date().addingTimeInterval(-568024668)
let drinkingAgeRule = ValidationRuleComparison<Date>(min: eighteenYearsAgo, error: validationError)
let dateOfBirth = Date().addingTimeInterval(-662695446) // 21 years old
dateOfBirth.validate(rule: rule) // -> .valid

... or that a number is within a specified range:

let numericRule = ValidationRuleComparison<Int>(min: 50, max: 100, error: validationError)
42.validate(numericRule) // -> .invalid(validationError)

.. or that a text field contains a valid Visa or American Express card number:

let cardRule = ValidationRulePaymentCard(availableTypes: [.visa, .amex], error: validationError)
paymentCardTextField.validate(cardRule) // -> .valid or .invalid(validationError) depending on what's in paymentCardTextField

Features

  • Validation rules:
    • Required
    • Equality
    • Comparison
    • Length (min, max, range)
    • Pattern (email, password constraints and more...)
    • Contains
    • URL
    • Payment card (Luhn validated, accepted types)
    • Condition (quickly write your own)
  • Swift standard library type extensions with one API (not just strings!)
  • UIKit element extensions
  • Open validation error types
  • An open protocol-oriented implementation
  • Comprehensive test coverage
  • Comprehensive code documentation

Demo

demo-vid

Installation

CocoaPods

CocoaPods Compatible CocoaPods Compatible

pod 'Validator'

Carthage

Carthage Compatible

github "adamwaite/Validator"

Usage

Validator can validate any Validatable type using one or multiple ValidationRules. A validation operation returns a ValidationResult which matches either .valid or .invalid([Error]).

let rule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: validationError)

let result = "invalid@email,com".validate(rule: rule)
// Note: the above is equivalent to Validator.validate(input: "invalid@email,com", rule: rule)

switch result {
case .valid: print("😀")
case .invalid(let failures): print(failures.first?.message)
}

Validation Rules

Required

Validates a type exists (not-nil).

let stringRequiredRule = ValidationRuleRequired<String?>(error: validationError)

let floatRequiredRule = ValidationRuleRequired<Float?>(error: validationError)

Note - You can't use validate on an optional Validatable type (e.g. myString?.validate(aRule...) because the optional chaining mechanism will bypass the call. "thing".validate(rule: aRule...) is fine. To validate an optional for required in this way use: Validator.validate(input: anOptional, rule: aRule).

Equality

Validates an Equatable type is equal to another.

let staticEqualityRule = ValidationRuleEquality<String>(target: "hello", error: validationError)

let dynamicEqualityRule = ValidationRuleEquality<String>(dynamicTarget: { return textField.text ?? "" }, error: validationError)

Comparison

Validates a Comparable type against a maximum and minimum.

let comparisonRule = ValidationRuleComparison<Float>(min: 5, max: 7, error: validationError)

Length

Validates a String length satisfies a minimum, maximum or range.

let minLengthRule = ValidationRuleLength(min: 5, error: validationError)

let maxLengthRule = ValidationRuleLength(max: 5, error: validationError)

let rangeLengthRule = ValidationRuleLength(min: 5, max: 10, error: validationError)

Pattern

Validates a String against a pattern.

ValidationRulePattern can be initialised with a String pattern or a type conforming to ValidationPattern. Validator provides some common patterns in the Patterns directory.

let emailRule = ValidationRulePattern(pattern: EmailValidationPattern.standard, error: validationError)

let digitRule = ValidationRulePattern(pattern: ContainsNumberValidationPattern(), error: someValidationErrorType)

let helloRule = ValidationRulePattern(pattern: ".*hello.*", error: validationError)

Contains

Validates an Equatable type is within a predefined SequenceType's elements (where the Element of the SequenceType matches the input type).

let stringContainsRule = ValidationRuleContains<String, [String]>(sequence: ["hello", "hi", "hey"], error: validationError)

let rule = ValidationRuleContains<Int, [Int]>(sequence: [1, 2, 3], error: validationError)

URL

Validates a String to see if it's a valid URL conforming to RFC 2396.

let urlRule = ValidationRuleURL(error: validationError)

Payment Card

Validates a String to see if it's a valid payment card number by firstly running it through the Luhn check algorithm, and secondly ensuring it follows the format of a number of payment card providers.

public enum PaymentCardType: Int {
    case amex, mastercard, visa, maestro, dinersClub, jcb, discover, unionPay
    ///...

To be validate against any card type (just the Luhn check):

let anyCardRule = ValidationRulePaymentCard(error: validationError)

To be validate against a set of accepted card types (e.g Visa, Mastercard and American Express in this example):

let acceptedCardsRule = ValidationRulePaymentCard(acceptedTypes: [.visa, .mastercard, .amex], error: validationError)

Condition

Validates a Validatable type with a custom condition.

let conditionRule = ValidationRuleCondition<[String]>(error: validationError) { $0.contains("Hello") }

Create Your Own

Create your own validation rules by conforming to the ValidationRule protocol:

protocol ValidationRule {
    typealias InputType
    func validate(input: InputType) -> Bool
    var error: ValidationError { get }
}

Example:

struct HappyRule {
    typealias InputType = String
    var error: ValidationError
    func validate(input: String) -> Bool {
        return input == "😀"
    }
}

If your custom rule doesn't already exist in the library and you think it might be useful for other people, then it'd be great if you added it in with a pull request.

Multiple Validation Rules (ValidationRuleSet)

Validation rules can be combined into a ValidationRuleSet containing a collection of rules that validate a type.

var passwordRules = ValidationRuleSet<String>()

let minLengthRule = ValidationRuleLength(min: 5, error: validationError)
passwordRules.add(rule: minLengthRule)

let digitRule = ValidationRulePattern(pattern: .ContainsDigit, error: validationError)
passwordRules.add(rule: digitRule)

Validatable

Any type that conforms to the Validatable protocol can be validated using the validate: method.

// Validate with a single rule:

let result = "some string".validate(rule: aRule)

// Validate with a collection of rules:

let result = 42.validate(rules: aRuleSet)

Extend Types As Validatable

Extend the Validatable protocol to make a new type validatable.

extension Thing : Validatable { }

Note: The implementation inside the protocol extension should mean that you don't need to implement anything yourself unless you need to validate multiple properties.

ValidationResult

The validate: method returns a ValidationResult enum. ValidationResult can take one of two forms:

  1. .valid: The input satisfies the validation rules.
  2. .invalid: The input fails the validation rules. An .invalid result has an associated array of types conforming to ValidationError.

Errors

Initialize rules with any ValidationError to be passed with the result on a failed validation.

Example:

struct User: Validatable {

    let email: String

    enum ValidationErrors: String, ValidationError {
        case emailInvalid = "Email address is invalid"
        var message { return self.rawValue }
    }

    func validate() -> ValidationResult {
        let rule ValidationRulePattern(pattern: .emailAddress, error: ValidationErrors.emailInvalid)
        return email.validate(rule: rule)
    }
}

Validating UIKit Elements

UIKit elements that conform to ValidatableInterfaceElement can have their input validated with the validate: method.

let textField = UITextField()
textField.text = "I'm going to be validated"

let slider = UISlider()
slider.value = 0.3

// Validate with a single rule:

let result = textField.validate(rule: aRule)

// Validate with a collection of rules:

let result = slider.validate(rules: aRuleSet)

Validate On Input Change

A ValidatableInterfaceElement can be configured to automatically validate when the input changes in 3 steps.

  1. Attach a set of default rules:

    let textField = UITextField()
    var rules = ValidationRuleSet<String>()
    rules.add(rule: someRule)
    textField.validationRules = rules
  2. Attach a closure to fire on input change:

    textField.validationHandler = { result in
      switch result {
      case .valid:
    	    print("valid!")
      case .invalid(let failureErrors):
    	    let messages = failureErrors.map { $0.message }
        print("invalid!", messages)
      }
    }
  3. Begin observation:

    textField.validateOnInputChange(enabled: true)

Note - Use .validateOnInputChange(enabled: false) to end observation.

Extend UI Elements As Validatable

Extend the ValidatableInterfaceElement protocol to make an interface element validatable.

Example:

extension UITextField: ValidatableInterfaceElement {

    typealias InputType = String

    var inputValue: String { return text ?? "" }

    func validateOnInputChange(enabled: Bool) {
        switch validationEnabled {
        case true: addTarget(self, action: #selector(validateInputChange), forControlEvents: .editingChanged)
        case false: removeTarget(self, action: #selector(validateInputChange), forControlEvents: .editingChanged)
        }
    }

    @objc private func validateInputChange(_ sender: UITextField) {
        sender.validate()
    }

}

The implementation inside the protocol extension should mean that you should only need to implement:

  1. The typealias: the type of input to be validated (e.g String for UITextField).
  2. The inputValue: the input value to be validated (e.g the text value for UITextField).
  3. The validateOnInputChange: method: to configure input-change observation.

Examples

There's an example project in this repository.

Contributing

Any contributions and suggestions are most welcome! Please ensure any new code is covered with unit tests, and that all existing tests pass. Please update the README with any new features. Thanks!

Contact

@adamwaite

License

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 the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].