Compare commits

..

No commits in common. "master" and "swift-2.3" have entirely different histories.

29 changed files with 131 additions and 195 deletions

View File

@ -1,24 +1,15 @@
language: objective-c language: objective-c
osx_image: xcode8 osx_image: xcode7.1
xcode_sdk: iphonesimulator10.0
xcode_project: Validator.xcodeproj
xcode_scheme: Validator
before_install: before_install:
- gem install cocoapods -v '0.32.1'
- gem install xcpretty --no-rdoc --no-ri --no-document --quiet - gem install xcpretty --no-rdoc --no-ri --no-document --quiet
script: script:
- xcodebuild clean build test -project Validator.xcodeproj -scheme Validator -sdk iphonesimulator -destination "platform=iOS Simulator,OS=10.0,name=iPhone 6" -enableCodeCoverage YES CODE_SIGNING_REQUIRED=NO | xcpretty
- pod lib lint - pod lib lint
- xcodebuild clean build test -project Validator.xcodeproj -scheme Validator -sdk iphonesimulator9.1 -destination "OS=9.1,name=iPhone 6" -enableCodeCoverage YES | xcpretty
after_success: after_success:
- bash <(curl -s https://codecov.io/bash) - bash <(curl -s https://codecov.io/bash)
notifications:
webhooks:
urls:
- https://webhooks.gitter.im/e/4cfa929bd227586305cc
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always

View File

@ -1,7 +1,7 @@
SwiftValidator SwiftValidator
=============== ===============
[![Build Status](https://travis-ci.org/SwiftValidatorCommunity/SwiftValidator.svg?branch=master)](https://travis-ci.org/SwiftValidatorCommunity/SwiftValidator) [![codecov.io](https://codecov.io/github/SwiftValidatorCommunity/SwiftValidator/coverage.svg?branch=master)](https://codecov.io/github/SwiftValidatorCommunity/SwiftValidator?branch=master) [![Build Status](https://travis-ci.org/jpotts18/SwiftValidator.svg?branch=travis-ci)](https://travis-ci.org/jpotts18/SwiftValidator) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![codecov.io](https://codecov.io/github/jpotts18/SwiftValidator/coverage.svg?branch=master)](https://codecov.io/github/jpotts18/SwiftValidator?branch=master)
Swift Validator is a rule-based validation library for Swift. Swift Validator is a rule-based validation library for Swift.
@ -22,16 +22,11 @@ platform :ios, "8.1"
use_frameworks! use_frameworks!
# Swift 3 # As of 4.0.0, SwiftValidator has been extended beyond UITextField
# 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 # 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' pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '4.0.0'
# Swift 2.1 (limited to UITextField validation) # For older versions
pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '3.0.5' pod 'SwiftValidator', :git => 'https://github.com/jpotts18/SwiftValidator.git', :tag => '3.0.5'
``` ```
@ -82,7 +77,7 @@ override func viewDidLoad() {
// You can now pass in regex and length parameters through overloaded contructors // You can now pass in regex and length parameters through overloaded contructors
validator.registerField(phoneNumberTextField, errorLabel: phoneNumberErrorLabel, rules: [RequiredRule(), MinLengthRule(length: 9)]) validator.registerField(phoneNumberTextField, errorLabel: phoneNumberErrorLabel, rules: [RequiredRule(), MinLengthRule(length: 9)])
validator.registerField(zipcodeTextField, errorLabel: zipcodeErrorLabel, rules: [RequiredRule(), ZipCodeRule(regex : "\\d{5}")]) 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 // You can unregister a text field if you no longer want to validate it
validator.unregisterField(fullNameTextField) validator.unregisterField(fullNameTextField)
@ -107,16 +102,16 @@ func validationSuccessful() {
// submit the form // submit the form
} }
func validationFailed(_ errors:[(Validatable ,ValidationError)]) { func validationFailed(errors:[(Validatable ,ValidationError)]) {
// turn the fields to red // turn the fields to red
for (field, error) in errors { for (field, error) in errors {
if let field = field as? UITextField { if let field = field as? UITextField {
field.layer.borderColor = UIColor.red.cgColor field.layer.borderColor = UIColor.redColor().CGColor
field.layer.borderWidth = 1.0 field.layer.borderWidth = 1.0
} }
error.errorLabel?.text = error.errorMessage // works if you added labels error.errorLabel?.text = error.errorMessage // works if you added labels
error.errorLabel?.isHidden = false error.errorLabel?.hidden = false
} }
} }
``` ```
@ -159,7 +154,7 @@ class SSNVRule: RegexRule {
``` ```
## Documentation ## Documentation
Checkout the docs <a href="http://swiftvalidatorcommunity.github.io/SwiftValidator/">here</a> via [@jazzydocs](https://twitter.com/jazzydocs). Checkout the docs <a href="http://jpotts18.github.io/SwiftValidator/">here</a> via [@jazzydocs](https://twitter.com/jazzydocs).
Credits Credits

View File

@ -1,15 +1,15 @@
Pod::Spec.new do |s| Pod::Spec.new do |s|
s.name = "SwiftValidator" s.name = "SwiftValidator"
s.version = "4.0.2" s.version = "4.0.0"
s.summary = "A UITextField Validation library for Swift" s.summary = "A UITextField Validation library for Swift"
s.homepage = "https://github.com/TouchInstinct/SwiftValidator" s.homepage = "https://github.com/jpotts18/SwiftValidator"
s.screenshots = "https://raw.githubusercontent.com/jpotts18/SwiftValidator/master/swift-validator-v2.gif" s.screenshots = "https://raw.githubusercontent.com/jpotts18/SwiftValidator/master/swift-validator-v2.gif"
s.license = { :type => "MIT", :file => "LICENSE.txt" } s.license = { :type => "MIT", :file => "LICENSE.txt" }
s.author = { "Jeff Potter" => "jeff.potter6@gmail.com" } s.author = { "Jeff Potter" => "jeff.potter6@gmail.com" }
s.social_media_url = "http://twitter.com/jpotts18" s.social_media_url = "http://twitter.com/jpotts18"
s.platform = :ios s.platform = :ios
s.ios.deployment_target = '8.0' s.ios.deployment_target = '8.0'
s.source = { :git => "https://github.com/TouchInstinct/SwiftValidator.git", :tag => s.version } s.source = { :git => "https://github.com/jpotts18/SwiftValidator.git", :tag => "4.0.0" }
s.source_files = "SwiftValidator/**/*.swift" s.source_files = "SwiftValidator/**/*.swift"
s.exclude_files = "Validator/AppDelegate.swift" s.exclude_files = "Validator/AppDelegate.swift"
s.frameworks = ['Foundation', 'UIKit'] s.frameworks = ['Foundation', 'UIKit']

View File

@ -8,7 +8,7 @@
import Foundation import Foundation
public typealias ValidatableField = AnyObject & Validatable public typealias ValidatableField = protocol<AnyObject, Validatable>
public protocol Validatable { public protocol Validatable {

View File

@ -23,5 +23,5 @@ public protocol ValidationDelegate {
- returns: No return value. - returns: No return value.
*/ */
func validationFailed(_ errors: [(Validatable, ValidationError)]) func validationFailed(errors: [(Validatable, ValidationError)])
} }

View File

@ -20,9 +20,9 @@ public class Validator {
/// Dictionary to hold fields by their object identifiers /// Dictionary to hold fields by their object identifiers
private var fields = ValidatorDictionary<Validatable>() private var fields = ValidatorDictionary<Validatable>()
/// Variable that holds success closure to display positive status of field. /// Variable that holds success closure to display positive status of field.
private var successStyleTransform:((_ validationRule:ValidationRule)->Void)? private var successStyleTransform:((validationRule:ValidationRule)->Void)?
/// Variable that holds error closure to display negative status of field. /// Variable that holds error closure to display negative status of field.
private var errorStyleTransform:((_ validationError:ValidationError)->Void)? private var errorStyleTransform:((validationError:ValidationError)->Void)?
/// - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. /// - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
public init(){} public init(){}
@ -44,13 +44,13 @@ public class Validator {
// let the user transform the field if they want // let the user transform the field if they want
if let transform = self.errorStyleTransform { if let transform = self.errorStyleTransform {
transform(error) transform(validationError: error)
} }
} else { } else {
// No error // No error
// let the user transform the field if they want // let the user transform the field if they want
if let transform = self.successStyleTransform { if let transform = self.successStyleTransform {
transform(rule) transform(validationRule: rule)
} }
} }
} }
@ -65,22 +65,22 @@ public class Validator {
- parameter field: Holds validator field data. - parameter field: Holds validator field data.
- returns: No return value. - returns: No return value.
*/ */
public func validateField(_ field: ValidatableField, callback: (_ error:ValidationError?) -> Void){ public func validateField(field: ValidatableField, callback: (error:ValidationError?) -> Void){
if let fieldRule = validations[field] { if let fieldRule = validations[field] {
if let error = fieldRule.validateField() { if let error = fieldRule.validateField() {
errors[field] = error errors[field] = error
if let transform = self.errorStyleTransform { if let transform = self.errorStyleTransform {
transform(error) transform(validationError: error)
} }
callback(error) callback(error: error)
} else { } else {
if let transform = self.successStyleTransform { if let transform = self.successStyleTransform {
transform(fieldRule) transform(validationRule: fieldRule)
} }
callback(nil) callback(error: nil)
} }
} else { } else {
callback(nil) callback(error: nil)
} }
} }
@ -93,7 +93,7 @@ public class Validator {
- parameter error: A closure which is called with validationError, an object that holds validation error data - parameter error: A closure which is called with validationError, an object that holds validation error data
- returns: No return value - returns: No return value
*/ */
public func styleTransformers(success:((_ validationRule:ValidationRule)->Void)?, error:((_ validationError:ValidationError)->Void)?) { public func styleTransformers(success success:((validationRule:ValidationRule)->Void)?, error:((validationError:ValidationError)->Void)?) {
self.successStyleTransform = success self.successStyleTransform = success
self.errorStyleTransform = error self.errorStyleTransform = error
} }
@ -106,7 +106,7 @@ public class Validator {
- parameter rules: A Rule array that holds different rules that apply to said field. - parameter rules: A Rule array that holds different rules that apply to said field.
- returns: No return value - returns: No return value
*/ */
public func registerField(_ field: ValidatableField, errorLabel:UILabel? = nil, rules:[Rule]) { public func registerField(field: ValidatableField, errorLabel:UILabel? = nil, rules:[Rule]) {
validations[field] = ValidationRule(field: field, rules:rules, errorLabel:errorLabel) validations[field] = ValidationRule(field: field, rules:rules, errorLabel:errorLabel)
fields[field] = field fields[field] = field
} }
@ -117,7 +117,7 @@ public class Validator {
- parameter field: field used to locate and remove field from validator. - parameter field: field used to locate and remove field from validator.
- returns: No return value - returns: No return value
*/ */
public func unregisterField(_ field:ValidatableField) { public func unregisterField(field:ValidatableField) {
validations.removeValueForKey(field) validations.removeValueForKey(field)
errors.removeValueForKey(field) errors.removeValueForKey(field)
} }
@ -127,7 +127,7 @@ public class Validator {
- returns: No return value. - returns: No return value.
*/ */
public func validate(_ delegate:ValidationDelegate) { public func validate(delegate:ValidationDelegate) {
self.validateAllFields() self.validateAllFields()
@ -145,10 +145,10 @@ public class Validator {
- parameter callback: A closure which is called with errors, a dictionary of type Validatable:ValidationError. - parameter callback: A closure which is called with errors, a dictionary of type Validatable:ValidationError.
- returns: No return value. - returns: No return value.
*/ */
public func validate(_ callback:(_ errors:[(Validatable, ValidationError)])->Void) -> Void { public func validate(callback:(errors:[(Validatable, ValidationError)])->Void) -> Void {
self.validateAllFields() self.validateAllFields()
callback(errors.map { (fields[$1.field]!, $1) } ) callback(errors: errors.map { (fields[$1.field]!, $1) } )
} }
} }

View File

@ -8,7 +8,7 @@
import Foundation import Foundation
public struct ValidatorDictionary<T> : Sequence { public struct ValidatorDictionary<T> : SequenceType {
private var innerDictionary: [ObjectIdentifier: T] = [:]; private var innerDictionary: [ObjectIdentifier: T] = [:];
@ -31,15 +31,15 @@ public struct ValidatorDictionary<T> : Sequence {
innerDictionary.removeAll() innerDictionary.removeAll()
} }
public mutating func removeValueForKey(_ key: ValidatableField) { public mutating func removeValueForKey(key: ValidatableField) {
innerDictionary.removeValue(forKey: ObjectIdentifier(key)) innerDictionary.removeValueForKey(ObjectIdentifier(key))
} }
public var isEmpty: Bool { public var isEmpty: Bool {
return innerDictionary.isEmpty return innerDictionary.isEmpty
} }
public func makeIterator() -> DictionaryIterator<ObjectIdentifier ,T> { public func generate() -> DictionaryGenerator<ObjectIdentifier ,T> {
return innerDictionary.makeIterator() return innerDictionary.generate()
} }
} }

View File

@ -21,6 +21,6 @@ public class AlphaNumericRule: CharacterSetRule {
- returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
*/ */
public init(message: String = "Enter valid numeric characters") { public init(message: String = "Enter valid numeric characters") {
super.init(characterSet: CharacterSet.alphanumerics, message: message) super.init(characterSet: NSCharacterSet.alphanumericCharacterSet(), message: message)
} }
} }

View File

@ -21,6 +21,6 @@ public class AlphaRule: CharacterSetRule {
- returns: An initialized object, or nil if an object could not be created for some reason. - returns: An initialized object, or nil if an object could not be created for some reason.
*/ */
public init(message: String = "Enter valid alphabetic characters") { public init(message: String = "Enter valid alphabetic characters") {
super.init(characterSet: CharacterSet.letters, message: message) super.init(characterSet: NSCharacterSet.letterCharacterSet(), message: message)
} }
} }

View File

@ -13,7 +13,7 @@ import Foundation
*/ */
public class CharacterSetRule: Rule { public class CharacterSetRule: Rule {
/// NSCharacter that hold set of valid characters to hold /// NSCharacter that hold set of valid characters to hold
private let characterSet: CharacterSet private let characterSet: NSCharacterSet
/// String that holds error message /// String that holds error message
private var message: String private var message: String
@ -24,7 +24,7 @@ public class CharacterSetRule: Rule {
- parameter message: String of error message. - parameter message: String of error message.
- returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception.
*/ */
public init(characterSet: CharacterSet, message: String = "Enter valid alpha") { public init(characterSet: NSCharacterSet, message: String = "Enter valid alpha") {
self.characterSet = characterSet self.characterSet = characterSet
self.message = message self.message = message
} }
@ -35,9 +35,9 @@ public class CharacterSetRule: Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails. - returns: Boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
for uni in value.unicodeScalars { for uni in value.unicodeScalars {
guard let uniVal = UnicodeScalar(uni.value), characterSet.contains(uniVal) else { if !characterSet.longCharacterIsMember(uni.value) {
return false return false
} }
} }
@ -52,4 +52,4 @@ public class CharacterSetRule: Rule {
public func errorMessage() -> String { public func errorMessage() -> String {
return message return message
} }
} }

View File

@ -37,7 +37,7 @@ public class ConfirmationRule: Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails. - returns: A boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
return confirmField.validationText == value return confirmField.validationText == value
} }
@ -49,4 +49,4 @@ public class ConfirmationRule: Rule {
public func errorMessage() -> String { public func errorMessage() -> String {
return message return message
} }
} }

View File

@ -26,7 +26,7 @@ public class ExactLengthRule : Rule {
*/ */
public init(length: Int, message : String = "Must be exactly %ld characters long"){ public init(length: Int, message : String = "Must be exactly %ld characters long"){
self.length = length self.length = length
self.message = String(format: message, self.length) self.message = NSString(format: message, self.length) as String
} }
/** /**
@ -35,8 +35,8 @@ public class ExactLengthRule : Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails. - returns: A boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
return value.count == length return value.characters.count == length
} }
/** /**
@ -47,4 +47,4 @@ public class ExactLengthRule : Rule {
public func errorMessage() -> String { public func errorMessage() -> String {
return message return message
} }
} }

View File

@ -31,10 +31,10 @@ public class FloatRule:Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails. - returns: Boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
let regex = try? NSRegularExpression(pattern: "^[-+]?(\\d*[.])?\\d+$", options: []) let regex = try? NSRegularExpression(pattern: "^[-+]?(\\d*[.])?\\d+$", options: [])
if let regex = regex { if let regex = regex {
let match = regex.numberOfMatches(in: value, options: [], range: NSRange(location: 0, length: value.count)) let match = regex.numberOfMatchesInString(value, options: [], range: NSRange(location: 0, length: value.characters.count))
return match == 1 return match == 1
} }
return false return false

View File

@ -30,8 +30,8 @@ public class FullNameRule : Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails. - returns: A boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
let nameArray: [String] = value.split { $0 == " " }.map { String($0) } let nameArray: [String] = value.characters.split { $0 == " " }.map { String($0) }
return nameArray.count >= 2 return nameArray.count >= 2
} }
@ -43,4 +43,4 @@ public class FullNameRule : Rule {
public func errorMessage() -> String { public func errorMessage() -> String {
return message return message
} }
} }

View File

@ -32,13 +32,13 @@ public class ISBNRule: Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails. - returns: Boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
guard let regex = try? NSRegularExpression(pattern: "[\\s-]", options: []) else { guard let regex = try? NSRegularExpression(pattern: "[\\s-]", options: []) else {
fatalError("Invalid ISBN sanitizing regex") fatalError("Invalid ISBN sanitizing regex")
} }
let sanitized = regex.stringByReplacingMatches(in: value, options: [], range: NSMakeRange(0, value.count), withTemplate: "") let sanitized = regex.stringByReplacingMatchesInString(value, options: [], range: NSMakeRange(0, value.characters.count), withTemplate: "")
return ISBN10Validator().verify(sanitized) || ISBN13Validator().verify(sanitized) return ISBN10Validator().verify(sanitized) || ISBN13Validator().verify(sanitized)
} }
@ -67,7 +67,7 @@ private protocol ISBNValidator {
- returns: A `Bool` that represents what happened during verification. `false` is returned if - returns: A `Bool` that represents what happened during verification. `false` is returned if
it fails, `true` is returned if it was a success. it fails, `true` is returned if it was a success.
*/ */
func verify(_ input: String) -> Bool func verify(input: String) -> Bool
/** /**
Method that verifies regular expression is valid. Method that verifies regular expression is valid.
@ -75,7 +75,7 @@ private protocol ISBNValidator {
- returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number - returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number
was not valid, `true` if it was valid. was not valid, `true` if it was valid.
*/ */
func checkRegex(_ input: String) -> Bool func checkRegex(input: String) -> Bool
/** /**
Method that verifies `ISBN` being validated is itself valid. It has to be either ISBN10 Method that verifies `ISBN` being validated is itself valid. It has to be either ISBN10
@ -85,7 +85,7 @@ private protocol ISBNValidator {
- returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number - returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number
was not valid, `true` if it was valid. was not valid, `true` if it was valid.
*/ */
func verifyChecksum(_ input: String) -> Bool func verifyChecksum(input: String) -> Bool
} }
/** /**
@ -100,7 +100,7 @@ extension ISBNValidator {
- returns: A `Bool` that represents what happened during verification. `false` is returned if - returns: A `Bool` that represents what happened during verification. `false` is returned if
it fails, `true` is returned if it was a success. it fails, `true` is returned if it was a success.
*/ */
func verify(_ input: String) -> Bool { func verify(input: String) -> Bool {
return checkRegex(input) && verifyChecksum(input) return checkRegex(input) && verifyChecksum(input)
} }
@ -112,8 +112,8 @@ extension ISBNValidator {
- returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number - returns: A `Bool` that represents the status of the ISBN number. `false` if ISBN number
was not valid, `true` if it was valid. was not valid, `true` if it was valid.
*/ */
func checkRegex(_ input: String) -> Bool { func checkRegex(input: String) -> Bool {
guard let _ = input.range(of: regex, options: [.regularExpression, .anchored]) else { guard let _ = input.rangeOfString(regex, options: [.RegularExpressionSearch, .AnchoredSearch]) else {
return false return false
} }
@ -136,19 +136,19 @@ private struct ISBN10Validator: ISBNValidator {
- parameter input: String that is checked for ISBN10 validation. - parameter input: String that is checked for ISBN10 validation.
- returns: `true` if string is a valid ISBN10 and `false` if it is not. - returns: `true` if string is a valid ISBN10 and `false` if it is not.
*/ */
fileprivate func verifyChecksum(_ input: String) -> Bool { private func verifyChecksum(input: String) -> Bool {
var checksum = 0 var checksum = 0
for i in 0..<9 { for i in 0..<9 {
if let intCharacter = Int(String(input[input.index(input.startIndex, offsetBy: i)])) { if let intCharacter = Int(String(input[input.startIndex.advancedBy(i)])) {
checksum += (i + 1) * intCharacter checksum += (i + 1) * intCharacter
} }
} }
if (input[input.index(input.startIndex, offsetBy: 9)] == "X") { if (input[input.startIndex.advancedBy(9)] == "X") {
checksum += 10 * 10 checksum += 10 * 10
} else { } else {
if let intCharacter = Int(String(input[input.index(input.startIndex, offsetBy: 9)])) { if let intCharacter = Int(String(input[input.startIndex.advancedBy(9)])) {
checksum += 10 * intCharacter checksum += 10 * intCharacter
} }
} }
@ -171,21 +171,21 @@ private struct ISBN13Validator: ISBNValidator {
- parameter input: String that is checked for ISBN13 validation. - parameter input: String that is checked for ISBN13 validation.
- returns: `true` if string is a valid ISBN13 and `false` if it is not. - returns: `true` if string is a valid ISBN13 and `false` if it is not.
*/ */
fileprivate func verifyChecksum(_ input: String) -> Bool { private func verifyChecksum(input: String) -> Bool {
let factor = [1, 3] let factor = [1, 3]
var checksum = 0 var checksum = 0
for i in 0..<12 { for i in 0..<12 {
if let intCharacter = Int(String(input[input.index(input.startIndex, offsetBy: i)])) { if let intCharacter = Int(String(input[input.startIndex.advancedBy(i)])) {
print("\(factor[i%2]) * \(intCharacter)") print("\(factor[i%2]) * \(intCharacter)")
checksum += factor[i % 2] * intCharacter checksum += factor[i % 2] * intCharacter
} }
} }
if let lastInt = Int(String(input[input.index(input.startIndex, offsetBy: 12)])) { if let lastInt = Int(String(input[input.startIndex.advancedBy(12)])) {
return (lastInt - ((10 - (checksum % 10)) % 10) == 0) return (lastInt - ((10 - (checksum % 10)) % 10) == 0)
} }
return false return false
} }
} }

View File

@ -27,7 +27,7 @@ public class MaxLengthRule: Rule {
*/ */
public init(length: Int, message : String = "Must be at most %ld characters long"){ public init(length: Int, message : String = "Must be at most %ld characters long"){
self.DEFAULT_LENGTH = length self.DEFAULT_LENGTH = length
self.message = String(format: message, self.DEFAULT_LENGTH) self.message = NSString(format: message, self.DEFAULT_LENGTH) as String
} }
/** /**
@ -36,8 +36,8 @@ public class MaxLengthRule: Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails. - returns: A boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
return value.count <= DEFAULT_LENGTH return value.characters.count <= DEFAULT_LENGTH
} }
/** /**

View File

@ -29,7 +29,7 @@ public class MinLengthRule: Rule {
*/ */
public init(length: Int, message : String = "Must be at least %ld characters long"){ public init(length: Int, message : String = "Must be at least %ld characters long"){
self.DEFAULT_LENGTH = length self.DEFAULT_LENGTH = length
self.message = String(format: message, self.DEFAULT_LENGTH) self.message = NSString(format: message, self.DEFAULT_LENGTH) as String
} }
/** /**
@ -37,8 +37,8 @@ public class MinLengthRule: Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails. - returns: A boolean value. True if validation is successful; False if validation fails.
*/ */
public func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
return value.count >= DEFAULT_LENGTH return value.characters.count >= DEFAULT_LENGTH
} }
/** /**

View File

@ -11,7 +11,7 @@ import Foundation
/** /**
`RegexRule` is a subclass of Rule that defines how a regular expression is validated. `RegexRule` is a subclass of Rule that defines how a regular expression is validated.
*/ */
open class RegexRule : Rule { public class RegexRule : Rule {
/// Regular express string to be used in validation. /// Regular express string to be used in validation.
private var REGEX: String = "^(?=.*?[A-Z]).{8,}$" private var REGEX: String = "^(?=.*?[A-Z]).{8,}$"
/// String that holds error message. /// String that holds error message.
@ -35,9 +35,9 @@ open class RegexRule : Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails. - returns: Boolean value. True if validation is successful; False if validation fails.
*/ */
open func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %@", self.REGEX) let test = NSPredicate(format: "SELF MATCHES %@", self.REGEX)
return test.evaluate(with: value) return test.evaluateWithObject(value)
} }
/** /**
@ -45,7 +45,7 @@ open class RegexRule : Rule {
- returns: String of error message. - returns: String of error message.
*/ */
open func errorMessage() -> String { public func errorMessage() -> String {
return message return message
} }
} }

View File

@ -11,7 +11,7 @@ import Foundation
/** /**
`RequiredRule` is a subclass of Rule that defines how a required field is validated. `RequiredRule` is a subclass of Rule that defines how a required field is validated.
*/ */
open class RequiredRule: Rule { public class RequiredRule: Rule {
/// String that holds error message. /// String that holds error message.
private var message : String private var message : String
@ -31,7 +31,7 @@ open class RequiredRule: Rule {
- parameter value: String to checked for validation. - parameter value: String to checked for validation.
- returns: Boolean value. True if validation is successful; False if validation fails. - returns: Boolean value. True if validation is successful; False if validation fails.
*/ */
open func validate(_ value: String) -> Bool { public func validate(value: String) -> Bool {
return !value.isEmpty return !value.isEmpty
} }
@ -40,7 +40,7 @@ open class RequiredRule: Rule {
- returns: String of error message. - returns: String of error message.
*/ */
open func errorMessage() -> String { public func errorMessage() -> String {
return message return message
} }
} }

View File

@ -17,7 +17,7 @@ public protocol Rule {
- parameter value: String of text to be validated. - parameter value: String of text to be validated.
- returns: Boolean value. True if validation is successful; False if validation fails. - returns: Boolean value. True if validation is successful; False if validation fails.
*/ */
func validate(_ value: String) -> Bool func validate(value: String) -> Bool
/** /**
Displays error message of a field that has failed validation. Displays error message of a field that has failed validation.

View File

@ -39,7 +39,7 @@ public class ValidationRule {
*/ */
public func validateField() -> ValidationError? { public func validateField() -> ValidationError? {
return rules.filter{ return rules.filter{
return !$0.validate(field.validationText) return !$0.validate(field.validationText ?? "")
}.map{ rule -> ValidationError in return ValidationError(field: self.field, errorLabel:self.errorLabel, error: rule.errorMessage()) }.first }.map{ rule -> ValidationError in return ValidationError(field: self.field, errorLabel:self.errorLabel, error: rule.errorMessage()) }.first
} }
} }

View File

@ -366,7 +366,7 @@ class SwiftValidatorTests: XCTestCase {
} }
REGISTER_TXT_FIELD.text = INVALID_EMAIL REGISTER_TXT_FIELD.text = INVALID_EMAIL
REGISTER_VALIDATOR.validateField(REGISTER_TXT_FIELD) { error in REGISTER_VALIDATOR.validateField(REGISTER_TXT_FIELD) { error in
XCTAssert(error?.errorMessage.count ?? 0 > 0, "Should state 'invalid email'") XCTAssert(error?.errorMessage.characters.count > 0, "Should state 'invalid email'")
} }
} }
@ -385,9 +385,9 @@ class SwiftValidatorTests: XCTestCase {
var successCount = 0 var successCount = 0
var errorCount = 0 var errorCount = 0
REGISTER_VALIDATOR.styleTransformers(success: { (validationRule) -> Void in REGISTER_VALIDATOR.styleTransformers(success: { (validationRule) -> Void in
successCount+=1 successCount++
}) { (validationError) -> Void in }) { (validationError) -> Void in
errorCount+=1 errorCount++
} }
REGISTER_TXT_FIELD.text = INVALID_EMAIL REGISTER_TXT_FIELD.text = INVALID_EMAIL
REGISTER_VALIDATOR.validate { (errors) -> Void in REGISTER_VALIDATOR.validate { (errors) -> Void in
@ -403,9 +403,9 @@ class SwiftValidatorTests: XCTestCase {
var successCount = 0 var successCount = 0
var errorCount = 0 var errorCount = 0
REGISTER_VALIDATOR.styleTransformers(success: { (validationRule) -> Void in REGISTER_VALIDATOR.styleTransformers(success: { (validationRule) -> Void in
successCount+=1 successCount++
}) { (validationError) -> Void in }) { (validationError) -> Void in
errorCount+=1 errorCount++
} }
REGISTER_TXT_FIELD.text = INVALID_EMAIL REGISTER_TXT_FIELD.text = INVALID_EMAIL
@ -427,7 +427,7 @@ class SwiftValidatorTests: XCTestCase {
REGISTER_TXT_FIELD.text = INVALID_EMAIL REGISTER_TXT_FIELD.text = INVALID_EMAIL
REGISTER_VALIDATOR.validate { (errors) -> Void in REGISTER_VALIDATOR.validate { (errors) -> Void in
XCTAssert(errors.count == 1, "Should come back with errors") XCTAssert(errors.count == 1, "Should come back with errors")
XCTAssert(!(self.REGISTER_TXT_FIELD.layer.borderColor! == UIColor.red.cgColor), "Color shouldn't get set at all") XCTAssert(!CGColorEqualToColor(self.REGISTER_TXT_FIELD.layer.borderColor, UIColor.redColor().CGColor), "Color shouldn't get set at all")
} }
} }
} }

View File

@ -396,25 +396,21 @@
attributes = { attributes = {
LastSwiftMigration = 0700; LastSwiftMigration = 0700;
LastSwiftUpdateCheck = 0700; LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0930; LastUpgradeCheck = 0700;
ORGANIZATIONNAME = jpotts18; ORGANIZATIONNAME = jpotts18;
TargetAttributes = { TargetAttributes = {
62D1AE161A1E6D4400E4DFF8 = { 62D1AE161A1E6D4400E4DFF8 = {
CreatedOnToolsVersion = 6.1; CreatedOnToolsVersion = 6.1;
LastSwiftMigration = 0800;
}; };
62D1AE2B1A1E6D4500E4DFF8 = { 62D1AE2B1A1E6D4500E4DFF8 = {
CreatedOnToolsVersion = 6.1; CreatedOnToolsVersion = 6.1;
LastSwiftMigration = 0800;
TestTargetID = 62D1AE161A1E6D4400E4DFF8; TestTargetID = 62D1AE161A1E6D4400E4DFF8;
}; };
FB465CB21B9884F400398388 = { FB465CB21B9884F400398388 = {
CreatedOnToolsVersion = 6.4; CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 1010;
}; };
FB465CBC1B9884F400398388 = { FB465CBC1B9884F400398388 = {
CreatedOnToolsVersion = 6.4; CreatedOnToolsVersion = 6.4;
LastSwiftMigration = 1010;
TestTargetID = 62D1AE161A1E6D4400E4DFF8; TestTargetID = 62D1AE161A1E6D4400E4DFF8;
}; };
}; };
@ -584,23 +580,13 @@
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
@ -609,7 +595,6 @@
ENABLE_TESTABILITY = YES; ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99; GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO; GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0; GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = ( GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1", "DEBUG=1",
@ -627,7 +612,6 @@
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos; SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 4.0;
}; };
name = Debug; name = Debug;
}; };
@ -639,23 +623,13 @@
CLANG_CXX_LIBRARY = "libc++"; CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES; CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
@ -663,7 +637,6 @@
ENABLE_NS_ASSERTIONS = NO; ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99; GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNDECLARED_SELECTOR = YES;
@ -673,8 +646,6 @@
IPHONEOS_DEPLOYMENT_TARGET = 8.0; IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos; SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_VERSION = 4.0;
VALIDATE_PRODUCT = YES; VALIDATE_PRODUCT = YES;
}; };
name = Release; name = Release;
@ -687,7 +658,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.2;
}; };
name = Debug; name = Debug;
}; };
@ -699,8 +669,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 4.2;
}; };
name = Release; name = Release;
}; };
@ -716,7 +684,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.1;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator";
}; };
name = Debug; name = Debug;
@ -729,7 +696,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.1;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator";
}; };
name = Release; name = Release;
@ -737,7 +703,6 @@
FB465CCC1B9884F400398388 /* Debug */ = { FB465CCC1B9884F400398388 /* Debug */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
CODE_SIGN_IDENTITY = "";
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEFINES_MODULE = YES; DEFINES_MODULE = YES;
@ -755,7 +720,6 @@
PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_VERSION = 4.2;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = ""; VERSION_INFO_PREFIX = "";
@ -765,7 +729,6 @@
FB465CCD1B9884F400398388 /* Release */ = { FB465CCD1B9884F400398388 /* Release */ = {
isa = XCBuildConfiguration; isa = XCBuildConfiguration;
buildSettings = { buildSettings = {
CODE_SIGN_IDENTITY = "";
COPY_PHASE_STRIP = NO; COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1; CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
@ -780,8 +743,6 @@
PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "me.jeffpotter.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES; SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 4.2;
TARGETED_DEVICE_FAMILY = "1,2"; TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic"; VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = ""; VERSION_INFO_PREFIX = "";
@ -806,7 +767,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.levous.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "com.levous.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 4.2;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator";
}; };
name = Debug; name = Debug;
@ -826,8 +786,6 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.levous.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_BUNDLE_IDENTIFIER = "com.levous.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
SWIFT_VERSION = 4.2;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Validator.app/Validator";
}; };
name = Release; name = Release;

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0930" LastUpgradeVersion = "0700"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0930" LastUpgradeVersion = "0700"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"
@ -26,8 +26,8 @@
buildConfiguration = "Debug" buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
codeCoverageEnabled = "YES" shouldUseLaunchSchemeArgsEnv = "YES"
shouldUseLaunchSchemeArgsEnv = "YES"> codeCoverageEnabled = "YES">
<Testables> <Testables>
<TestableReference <TestableReference
skipped = "NO"> skipped = "NO">

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<Scheme <Scheme
LastUpgradeVersion = "0930" LastUpgradeVersion = "0700"
version = "1.3"> version = "1.3">
<BuildAction <BuildAction
parallelizeBuildables = "YES" parallelizeBuildables = "YES"

View File

@ -14,30 +14,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch. // Override point for customization after application launch.
return true return true
} }
func applicationWillResignActive(_ application: UIApplication) { func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
} }
func applicationDidEnterBackground(_ application: UIApplication) { func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
} }
func applicationWillEnterForeground(_ application: UIApplication) { func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
} }
func applicationDidBecomeActive(_ application: UIApplication) { func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
} }
func applicationWillTerminate(_ application: UIApplication) { func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
} }

View File

@ -31,24 +31,24 @@ class ViewController: UIViewController , ValidationDelegate, UITextFieldDelegate
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.hideKeyboard))) self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "hideKeyboard"))
validator.styleTransformers(success:{ (validationRule) -> Void in validator.styleTransformers(success:{ (validationRule) -> Void in
print("here") print("here")
// clear error label // clear error label
validationRule.errorLabel?.isHidden = true validationRule.errorLabel?.hidden = true
validationRule.errorLabel?.text = "" validationRule.errorLabel?.text = ""
if let textField = validationRule.field as? UITextField { if let textField = validationRule.field as? UITextField {
textField.layer.borderColor = UIColor.green.cgColor textField.layer.borderColor = UIColor.greenColor().CGColor
textField.layer.borderWidth = 0.5 textField.layer.borderWidth = 0.5
} }
}, error:{ (validationError) -> Void in }, error:{ (validationError) -> Void in
print("error") print("error")
validationError.errorLabel?.isHidden = false validationError.errorLabel?.hidden = false
validationError.errorLabel?.text = validationError.errorMessage validationError.errorLabel?.text = validationError.errorMessage
if let textField = validationError.field as? UITextField { if let textField = validationError.field as? UITextField {
textField.layer.borderColor = UIColor.red.cgColor textField.layer.borderColor = UIColor.redColor().CGColor
textField.layer.borderWidth = 1.0 textField.layer.borderWidth = 1.0
} }
}) })
@ -60,7 +60,7 @@ class ViewController: UIViewController , ValidationDelegate, UITextFieldDelegate
validator.registerField(zipcodeTextField, errorLabel: zipcodeErrorLabel, rules: [RequiredRule(), ZipCodeRule()]) validator.registerField(zipcodeTextField, errorLabel: zipcodeErrorLabel, rules: [RequiredRule(), ZipCodeRule()])
} }
@IBAction func submitTapped(_ sender: AnyObject) { @IBAction func submitTapped(sender: AnyObject) {
print("Validating...") print("Validating...")
validator.validate(self) validator.validate(self)
} }
@ -69,23 +69,23 @@ class ViewController: UIViewController , ValidationDelegate, UITextFieldDelegate
func validationSuccessful() { func validationSuccessful() {
print("Validation Success!") print("Validation Success!")
let alert = UIAlertController(title: "Success", message: "You are validated!", preferredStyle: UIAlertController.Style.alert) let alert = UIAlertController(title: "Success", message: "You are validated!", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(defaultAction) alert.addAction(defaultAction)
self.present(alert, animated: true, completion: nil) self.presentViewController(alert, animated: true, completion: nil)
} }
func validationFailed(_ errors:[(Validatable, ValidationError)]) { func validationFailed(errors:[(Validatable, ValidationError)]) {
print("Validation FAILED!") print("Validation FAILED!")
} }
@objc func hideKeyboard(){ func hideKeyboard(){
self.view.endEditing(true) self.view.endEditing(true)
} }
// MARK: Validate single field // MARK: Validate single field
// Don't forget to use UITextFieldDelegate // Don't forget to use UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool { func textFieldShouldReturn(textField: UITextField) -> Bool {
validator.validateField(textField){ error in validator.validateField(textField){ error in
if error == nil { if error == nil {
// Field validation was successful // Field validation was successful
@ -96,4 +96,4 @@ class ViewController: UIViewController , ValidationDelegate, UITextFieldDelegate
return true return true
} }
} }