Coder Social home page Coder Social logo

swift-validator's Introduction

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.0.6'

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}")])

}

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

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

Implement the Validation Delegate in your View controller

// ValidationDelegate methods

func validationWasSuccessful() {
	// 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

swift-validator's People

Contributors

jpotts18 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.