A rule-based validation library for Swift

Related tags

Form SwiftValidator
Overview

SwiftValidator

Build Status codecov.io

Swift Validator is a rule-based validation library for Swift.

Swift Validator

Core Concepts

  • UITextField + [Rule] + (and optional error UILabel) go into Validator
  • UITextField + ValidationError come out of Validator
  • Validator evaluates [Rule] sequentially and stops evaluating when a Rule fails.

Installation

# Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, "8.1"

use_frameworks!

# Swift 4.2
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '4.2.0'

# Swift 3
# Extended beyond UITextField
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :branch => 'master'

# Swift 2.1
# Extended beyond UITextField
# Note: Installing 4.x.x will break code from 3.x.x
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '4.0.0'

# Swift 2.1 (limited to UITextField validation)
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '3.0.5'

Install into your project:

$ pod install

Open your project in Xcode from the .xcworkspace file (not the usual project file):

$ open MyProject.xcworkspace

If you are using Carthage you will need to add this to your Cartfile

github "jpotts18/SwiftValidator"

Usage

You can now import SwiftValidator framework into your files.

Initialize the Validator by setting a delegate to a View Controller or other object.

// ViewController.swift
let validator = Validator()

Register the fields that you want to validate

override func viewDidLoad() {
	super.viewDidLoad()

	// Validation Rules are evaluated from left to right.
	validator.registerField(fullNameTextField, rules: [RequiredRule(), FullNameRule()])
	
	// You can pass in error labels with your rules
	// You can pass in custom error messages to regex rules (such as ZipCodeRule and EmailRule)
	validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])
	
	// You can validate against other fields using ConfirmRule
	validator.registerField(emailConfirmTextField, errorLabel: emailConfirmErrorLabel, rules: [ConfirmationRule(confirmField: emailTextField)])
	
	// You can now pass in regex and length parameters through overloaded contructors
	validator.registerField(phoneNumberTextField, errorLabel: phoneNumberErrorLabel, rules: [RequiredRule(), MinLengthRule(length: 9)])
	validator.registerField(zipcodeTextField, errorLabel: zipcodeErrorLabel, rules: [RequiredRule(), ZipCodeRule(regex : "\\d{5}")])

	// You can unregister a text field if you no longer want to validate it
	validator.unregisterField(fullNameTextField)
}

Validate Fields on button tap or however you would like to trigger it.

@IBAction func signupTapped(sender: AnyObject) {
	validator.validate(self)
}

Implement the Validation Delegate in your View controller

// ValidationDelegate methods

func validationSuccessful() {
	// submit the form
}

func validationFailed(_ errors:[(Validatable ,ValidationError)]) {
  // turn the fields to red
  for (field, error) in errors {
    if let field = field as? UITextField {
      field.layer.borderColor = UIColor.red.cgColor
      field.layer.borderWidth = 1.0
    }
    error.errorLabel?.text = error.errorMessage // works if you added labels
    error.errorLabel?.isHidden = false
  }
}

Single Field Validation

You may use single field validation in some cases. This could be useful in situations such as controlling responders:

// Don't forget to use UITextFieldDelegate
// and delegate yourTextField to self in viewDidLoad()
func textFieldShouldReturn(textField: UITextField) -> Bool {
    validator.validateField(textField){ error in
        if error == nil {
            // Field validation was successful
        } else {
            // Validation error occurred
        }
    }
    return true
}

Custom Validation

We will create a SSNRule class to show how to create your own Validation. A United States Social Security Number (or SSN) is a field that consists of XXX-XX-XXXX.

Create a class that inherits from RegexRule

class SSNVRule: RegexRule {

    static let regex = "^\\d{3}-\\d{2}-\\d{4}$"
	
    convenience init(message : String = "Not a valid SSN"){
	self.init(regex: SSNVRule.regex, message : message)
    }
}

Documentation

Checkout the docs here via @jazzydocs.

Credits

Swift Validator is written and maintained by Jeff Potter @jpotts18. David Patterson @dave_tw12 actively works as a collaborator. Special thanks to Deniz Adalar for adding validation beyond UITextField.

Contributing

  1. Fork it
  2. Create your feature branch git checkout -b my-new-feature
  3. Commit your changes git commit -am 'Add some feature'
  4. Push to the branch git push origin my-new-feature
  5. Create a new Pull Request
  6. Make sure code coverage is at least 70%
Comments
  • Error: An empty identity is not valid when signing a binary for the product type 'Application'. (in target 'Validator')

    Error: An empty identity is not valid when signing a binary for the product type 'Application'. (in target 'Validator')

    Hi guys:

    After updating to Xcode 10.2 and Swift 5, when executing carthage update I get the following error:

    error: An empty identity is not valid when signing a binary for the product type 'Application'. (in target 'Validator')

    Try again on a new project and throw the same error.

    Can someone help me please?

    Best regards.

    Adrián López Rendón

    opened by sargent-mg 10
  • Migrate to Swift 2.0

    Migrate to Swift 2.0

    Another option to close issue #37.

    I pulled master and ran through the Swift 2.0 migration using the Xcode 7 GM release. In this branch you should still see a full suite of passing tests, 0 warnings when build with the GM, and a version bump to 3.0.0 to account for the backwards incompatible change to Swift 2.0.

    I'd like to exercise this more completely but I still have some other 2.0 migration issues to fix before I can see it in action in my current app. All I can be completely confident of at the moment is that installation (via pod 'SwiftValidator', git: 'https://github.com/goodeggs/SwiftValidator.git', branch: 'swift-2.0') gives my app a Pods sub project which builds cleanly.

    opened by jonah-williams 9
  • Fix so that Rule can be subclassed

    Fix so that Rule can be subclassed

    Swift 3 is adding 2 more access levels (open and fileprivate) and changing the meaning of private:

    private: symbol visible within the current declaration only. fileprivate: symbol visible within the current file. internal: symbol visible within the current module. public: symbol visible outside the current module. open: for class or function to be subclassed or overridden outside the current module.

    In Swift 3 you can now mark a class as open instead of public this allows files outside of the module to subclass that class.

    opened by jspenc72 7
  • Is SwiftValidator compatible to Swift 3 ?

    Is SwiftValidator compatible to Swift 3 ?

    Pod updated to Swift3 pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :branch => 'swift3'

    but still getting many errors

    before it I used "swift3-dave" with lot of errors

    opened by bilawal-liaqat 7
  • fix #115: support for longer domain names from ICANN

    fix #115: support for longer domain names from ICANN

    Removes the limitation of 6 character to the domain, as it is not in ICANN anymore.

    I still would like to know why there is the need to double escape the . in

    \\.
    
    opened by racer1988 7
  • Bound value in a conditional binding must be of Optional type in Xcode 6.3

    Bound value in a conditional binding must be of Optional type in Xcode 6.3

    As per subject, I got this error message on this line of code

    import Foundation
    
    class PhoneNumberValidation: Validation {
        let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
    
        func validate(value: String) -> (Bool, ValidationErrorType) {
            if let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) { //error here
                if phoneTest.evaluateWithObject(value) {
                    return (true, .NoError)
                }
                return (false, .PhoneNumber)
            }
            return (false, .PhoneNumber)
        }
    
    }
    

    Please advice. Thank you.

    opened by datomnurdin 7
  • Validator returns all error messages associated with textfield

    Validator returns all error messages associated with textfield

    Hi Is there a way where the validator returns all the error messages associated with the textfield rather than just returning the error message associated to the first rule that it fails on?

    For example a text field has a RequiredRule(), MinLengthRule(6), RegexRule(1digit), RegexRule(1letter).

    When the user focuses on this textfield a message is displayed stating:

    "This is a required field. Minimum Length 6. One number. One Letter."

    As each rule is satisfied the message associated with that rule disappears.

    Thanks

    opened by w007up 6
  • Support for other input fields

    Support for other input fields

    It can be common to put an "age gate" on a signup form. I'm currently using a switch element for this. It would be useful to be able to add a validation rule that checks switch.on == true. I'm going to check that in the validationSuccessful delegate method before I submit the form but that doesn't give me the ability to have the validationFailed delegate method handle the error case for me.

    If I can find the time, I may try to do this myself and will send a pull request if I do but wanted to register this in case others have a similar need or the time to implement.

    Thanks for sharing this framework!

    opened by jdschmitt 6
  • Cocoapods and swift 1.1 support

    Cocoapods and swift 1.1 support

    Hi there,

    Was able to use swift-validator properly in a project, worked great, but wanted to add it through pods, these pull request lets you use it, configuring the Podfile to something like this (of course after pull request it can be pointed to the main repo)

    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, "8.1"
    use_frameworks!
    
    pod 'Swift-Validator', :git => 'https://github.com/asotog/swift-validator'
    

    Also updated the code to support previous version of swift, swift 1.2 still beta i think so better to still using previous

    Thanks in advance

    opened by asotog 6
  • cannot inherit from non-open class RegexRule outside of its defining module

    cannot inherit from non-open class RegexRule outside of its defining module

    import SwiftValidator
    class NumberRule: RegexRule {
    
        //Only allow integers
        static let regex = "^[0-9]*$"
    
        convenience init(message : String = "Not a valid number"){
            self.init(regex: NumberRule.regex, message : message)
        }
    }
    

    Must RegexRule be open instead of public? :

    Swift 3 is adding 2 more access levels (open and fileprivate) and changing the meaning of private:

    private: symbol visible within the current declaration only. fileprivate: symbol visible within the current file. internal: symbol visible within the current module. public: symbol visible outside the current module. open: for class or function to be subclassed or overridden outside the current module.

    opened by kiwo12345 5
  • Unable to install with Carthage

    Unable to install with Carthage

    Hi,

    I've been trying to install SwiftValidator for some time now and, although I'm inexperienced, it seems to me that the issue might not be my fault 😀 ...

    $ xcodebuild -version                                                          
    Xcode 7.3.1
    Build version 7D1014```
    
    xcode-select -p                                                              
    /Applications/Xcode.app/Contents/Developer
    

    This is the log:

    *** Fetching SwiftValidator
    *** Checking out SwiftValidator at "4.0.1"
    *** xcodebuild output can be found in      /var/folders/y_/266qdqcn20ngwdxwgnplctym0000gn/T/carthage-xcodebuild.O0M7Qv.log
    *** Building scheme "SwiftValidator" in Validator.xcodeproj
    2016-09-05 10:45:12.754 xcodebuild[89784:6467413] [MT] PluginLoading: Required plug-in compatibility UUID ACA8656B-FEA8-4B6D-8E4A-93F4C95C362C for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Alcatraz.xcplugin' not present in DVTPlugInCompatibilityUUIDs
    ** BUILD FAILED **
    
    The following build commands failed:
            CompileSwift normal arm64
            CompileSwiftSources normal arm64 com.apple.xcode.tools.swift.compiler
    (2 failures)
    

    And then comes a long list of errors.

    Is this an issue or is something specifically related to my install?

    opened by jonathan-soifer 5
  • HIPAA policy compliance

    HIPAA policy compliance

    I am trying to contribute to this repo but first I am facing some issues. Maybe I did not get the documentation right.

    I'm trying to add SpecialCharacterRule.swift

    class SpecialCharacterRule: RegexRule {
    
        static let regex = "[!\"#$%&'()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~]+"
    
        convenience init(message : String = "Password must contain %1$s or more special characters"){
            self.init(regex: SpecialCharacterRule.regex, message : message)
        }
    }
    

    NumericalSequencesRule.swift

    class NumericalSequencesRule: RegexRule {
    
        static let regex = ##"^(?:0(?=1|$))?(?:1(?=2|$))?(?:2(?=3|$))?(?:3(?=4|$))?(?:4(?=5|$))?(?:5(?=6|$))?(?:6(?=7|$))?(?:7(?=8|$))?(?:8(?=9|$))?(?:9$)?$"##
    
        convenience init(message : String = "Password contains the illegal numerical sequence '%1$s"){
            self.init(regex: NumericalSequencesRule.regex, message : message)
        }
    }
    

    and QwertyRule.swift

    class QwertyRule: RegexRule {
    
        static let regex = ##".*\\b\qwerty\\b.*"##
        
        convenience init(message : String = "Password contains the illegal QWERTY sequence '%1$s"){
            self.init(regex: QwertyRule.regex, message : message)
        }
    }
    

    Am I missing something? Why the conditions are not working? Meaning: SpecialCharacterRule, NumericalSequencesRule & QwertyRule does not pass and always returns invalid state !??!

    opened by alexszilagyi 0
  • Swift Package Manager support

    Swift Package Manager support

    Due to the failure of Cocoapods and Carthage on Xcode12 I had to add the framework using Swift Package Manager, I'm creating the PR in case it results useful for someone else.

    opened by lbatr3s 3
  • ValidationResult error

    ValidationResult error

    If you install the latest version of SwiftValidator and you get an error inside the ValidationResult.swift file make sure you add "return" inform of "self == .valid" like so:

     public var isValid: Bool {
        
        return self == .valid // add return infront
    }
    
    opened by tsangaris 0
Releases(5.0.0)
Owner
null
iOS Validation Library

Honour Validation library for iOS inspired by Respect/Validation. Validator.mustBe(Uppercase()).andMust(StartsWith("F")).validate("FOOBAR") ❗ If you w

Jean Pimentel 55 Jun 3, 2021
Declarative data validation framework, written in Swift

Peppermint Introduction Requirements Installation Swift Package Manager Usage Examples Predicates Constraints Predicate Constraint Compound Constraint

iOS NSAgora 43 Nov 22, 2022
Custom Field component with validation for creating easier form-like UI from interface builder.

#YALField Custom Field component with validation for creating easier form-like UI from interface builder. ##Example Project To run the example project

Yalantis 476 Sep 1, 2022
APValidators - Codeless solution for form validation in iOS!

APValidators is a codeless solution for form validation. Just connect everything right in Interface Builder and you're done. Supports really complex and extendable forms by allowing to connect validators in tree.

Alty 131 Aug 16, 2022
Former is a fully customizable Swift library for easy creating UITableView based form.

Former is a fully customizable Swift library for easy creating UITableView based form. Submitting Issues Click HERE to get started with filing a bug r

Ryo Aoyama 1.3k Dec 27, 2022
Carbon🚴 A declarative library for building component-based user interfaces in UITableView and UICollectionView.

A declarative library for building component-based user interfaces in UITableView and UICollectionView. Declarative Component-Based Non-Destructive Pr

Ryo Aoyama 1.2k Jan 5, 2023
SwiftForms is a small and lightweight library written in Swift that allows you to easily create forms.

SwiftForms is a powerful and extremely flexible library written in Swift that allows to create forms by just defining them in a couple of lines. It also provides the ability to customize cells appearance, use custom cells and define your own selector controllers.

Miguel Ángel Ortuño 1.3k Dec 27, 2022
XLForm is the most flexible and powerful iOS library to create dynamic table-view forms. Fully compatible with Swift & Obj-C.

XLForm By XMARTLABS. If you are working in Swift then you should have a look at Eureka, a complete re-design of XLForm in Swift and with more features

xmartlabs 5.8k Jan 6, 2023
ObjectForm - a simple yet powerful library to build form for your class models.

ObjectForm A simple yet powerful library to build form for your class models. Motivations I found most form libraries for swift are too complicated to

jakehao 175 Nov 2, 2022
Elegant iOS form builder in Swift

Made with ❤️ by XMARTLABS. This is the re-creation of XLForm in Swift. 简体中文 Overview Contents Requirements Usage How to create a Form Getting row valu

xmartlabs 11.6k Jan 1, 2023
Custom-TopBarController - A Custom TopBar Controller With Swift

TopBarController Верстка Для IPhone и IPod вертска адаптивная, для IPad frane To

Fadeev Sergey 1 Aug 2, 2022
GrouponHeader - iOS TableView Header Animation, Swift/UIKit

GrouponHeader Description: iOS TableView Header Animation Technology: Swift, UIK

James Sedlacek 8 Dec 15, 2022
AtomicReferenceCell - Atomic Reference Cell (Arc) for Swift

Atomic Reference Cell This project provide two structures: Arc<T> and WeakArc<T>

cjw 0 Jan 30, 2022
A rule-based validation library for Swift

SwiftValidator Swift Validator is a rule-based validation library for Swift. Core Concepts UITextField + [Rule] + (and optional error UILabel) go into

null 1.4k Dec 29, 2022
iOS validation framework with form validation support

ATGValidator ATGValidator is a validation framework written to address most common issues faced while verifying user input data. You can use it to val

null 51 Oct 19, 2022
iOS validation framework with form validation support

ATGValidator ATGValidator is a validation framework written to address most common issues faced while verifying user input data. You can use it to val

null 51 Oct 19, 2022
Type-based input validation.

Ensure Type-based input validation try Ensure<PackageIsCool>(wrappedValue: packages.ensure) Validators A Validator is a type that validates an input.

Build Passed 5 Jan 22, 2022
SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations.

SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations. Objective Build a stan

Andres Canal 542 Sep 17, 2022
🚦 Validation library depends on SwiftUI & Combine. Reactive and fully customizable.

?? Validation library depends on SwiftUI & Combine. Reactive and fully customizable.

Alexo 14 Dec 30, 2022
iOS Validation Library

Honour Validation library for iOS inspired by Respect/Validation. Validator.mustBe(Uppercase()).andMust(StartsWith("F")).validate("FOOBAR") ❗ If you w

Jean Pimentel 55 Jun 3, 2021