Go to file
mla2c ba9615cc85 Changes from leodasvacas fork (Custom messages for regex rules, commit 157e9791fb) 2015-06-01 14:13:26 +02:00
Validator Changes from leodasvacas fork (Custom messages for regex rules, commit 157e9791fb) 2015-06-01 14:13:26 +02:00
Validator.xcodeproj added float rule with tests 2015-05-05 18:58:11 -06:00
ValidatorTests cleaned up code, fixed tests 2015-05-06 11:44:25 -06:00
.gitignore fixed untracked files 2015-03-30 15:46:41 -06:00
LICENSE.txt adding license and reworking podspec 2015-04-03 22:20:54 -06:00
README.md updating readme, fixing extraneous # in parameter 2015-05-06 13:41:04 -06:00
SwiftValidator.podspec updating readme, fixing extraneous # in parameter 2015-05-06 13:41:04 -06:00
swift-validator-v2.gif fixing gif 2015-03-06 15:52:13 -07:00

README.md

SwiftValidator

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.

Quick Start

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

use_frameworks!
pod 'SwiftValidator', '2.1.1' 

Install into your project:

$ pod install

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

$ open MyProject.xcworkspace

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
	validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule()])
	
	// 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(delegate:self)
}

Implement the Validation Delegate in your View controller

// ValidationDelegate methods

func validationSuccessful() {
	// submit the form
}

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

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 implements the Rule protocol


class SSNVRule: Rule {
    let REGEX = "^\\d{3}-\\d{2}-\\d{4}$"
    
    init(){}
    
    // allow for custom variables to be passed
    init(regex:String){
        self.REGEX = regex
    }
    
    func validate(value: String) -> Bool {
        if let ssnTest = NSPredicate(format: "SELF MATCHES %@", REGEX) {
            if ssnTest.evaluateWithObject(value) {
                return true
            }
            return false
        }
    }
    
    func errorMessage() -> String{
        return "Not a valid SSN"
    }
}

Credits

Swift Validator is written and maintained by Jeff Potter @jpotts18.

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