Go to file
David Patterson b9b9a65b74 Merge pull request #98 from davepatterson/remote-validation-tests
Remote validation tests
2016-03-05 03:00:31 -06:00
SwiftValidator added tests for remote-validation methods and a little refactoring 2016-03-03 23:20:52 -06:00
SwiftValidatorTests more minor edits 2016-03-03 23:27:21 -06:00
Validator more minor edits 2016-03-03 23:27:21 -06:00
Validator.xcodeproj Merge branch 'bhargavg-add-new-rules' 2016-02-22 21:42:35 -07:00
ValidatorTests Small chnages to Scheme and moving tests 2015-10-15 13:36:41 -06:00
docs updated readme and added docs 2016-02-14 15:28:31 -06:00
.gitignore Adding Carthage support 2015-10-15 12:06:44 -06:00
.travis.yml added codecov to travis 2016-02-16 01:21:43 -06:00
LICENSE.txt adding license and reworking podspec 2015-04-03 22:20:54 -06:00
README.md Added remote validation and updated README accordingly 2016-03-02 21:48:30 -06:00
SwiftValidator.podspec updated podspec to 3.0.4 2016-03-01 09:58:14 -06:00
swift-validator-v2.gif fixing gif 2015-03-06 15:52:13 -07:00

README.md

SwiftValidator

Build Status Carthage compatible 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!
pod 'SwiftValidator', '3.0.3' 

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(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
	}
}

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

Remote Validation

Register field to validator with remoteInfo parameter set

validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule()], remoteInfo: (urlString: "http://localhost:8000/emails/", error: "Email already in use"))

Implement ValidationDelegate's remoteValidationRequest method

func remoteValidationRequest(text: String, urlString: String, completion: (result: Bool) -> Void) {
    // Add email to urlString
    let newUrlString = "\(urlString)?email=\(text)" 
    YourNetworkingLibrary.request(.GET, newUrlString) { data -> Void in
     
        if data.httpResponse.statusCode == 404 {
        	// resource was not found, therefore the text (username, email, etc) is available
        	completion(result: true)
        }
        	
        if data.httpResponse.statusCode == 200 {
        	// resource was found, therefore the text (username, email, etc) is unavailable
        	completion(result: false)
        }
    }
// end of remoteValidationRequest method
}

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