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

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

'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' ">
# 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 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
Declarative form validator for SwiftUI.

SwiftUIFormValidator The world's easiest, most clean SwiftUI form validation. SwiftUIFormValidator A declarative SwiftUI form validation. Clean, simpl

Shaban Kamel 42 Dec 13, 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
Input Validation Done Right. A Swift DSL for Validating User Input using Allow/Deny Rules

Valid Input Validation Done Right. Have you ever struggled with a website with strange password requirements. Especially those crazy weird ones where

Mathias Quintero 37 Nov 3, 2022
RxValidator Easy to Use, Read, Extensible, Flexible Validation Checker.

RxValidator Easy to Use, Read, Extensible, Flexible Validation Checker. It can use without Rx. Requirements RxValidator is written in Swift 4.

GeumSang Yoo 153 Nov 17, 2022
String (and more) validation for iOS

Swift Validators ?? String validation for iOS. Contents Installation Walkthrough Usage Available validators License ReactiveSwift + SwiftValidators Wa

George Kaimakas 241 Nov 13, 2022
Drop in user input validation for your iOS apps.

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

Adam Waite 1.4k Dec 29, 2022
Validation plugin for Moya.Result

MoyaResultValidate Why? Sometimes we need to verify that the data returned by the server is reasonable, when Moya returns Result.success. JSON returne

Insect_QY 1 Dec 15, 2021
Input Mask is an Android & iOS native library allowing to format user input on the fly.

Migration Guide: v.6 This update brings breaking changes. Namely, the autocomplete flag is now a part of the CaretGravity enum, thus the Mask::apply c

red_mad_robot 548 Dec 20, 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
SwiftEmailValidator - A Swift implementation of an international email address syntax validator based on RFC5321 & RFC5322

SwiftEmailValidator A Swift implementation of an international email address syn

Dave Poirier 21 Oct 24, 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
Swift String Validator. Simple lib for ios to validate string and UITextFields text for some criterias

Swift String validator About Library for easy and fastest string validation based on сciterias. Instalation KKStringValidator is available through Coc

Kostya 17 Dec 21, 2019
A Payment Card UI & Validator for iOS

Description Caishen provides an easy-to-use text field to ask users for payment card information and to validate the input. It serves a similar purpos

Prolific Interactive 766 Dec 28, 2022
Declarative form validator for SwiftUI.

SwiftUIFormValidator The world's easiest, most clean SwiftUI form validation. SwiftUIFormValidator A declarative SwiftUI form validation. Clean, simpl

Shaban Kamel 42 Dec 13, 2022
A validator for postal codes with support for 200+ regions

PostalCodeValidator A validator for postal codes with support for 200+ regions. import Foundation import PostalCodeValidator if let validator = Posta

FormatterKit 211 Jun 17, 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