• Stars
    star
    495
  • Rank 88,974 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 9 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A framework to validate inputs of text fields and text views in a convenient way.

License Build Status codecov.io Platform Swift Twitter

FormValidatorSwift

The FormValidatorSwift framework allows you to validate inputs of text fields and text views in a convenient way. It has been developed and used by iOS developers at ustwo.

Features

  • Simply use ValidatorTextField instead of UITextField or NSTextField (ValidatorTextView instead of UITextView or NSTextView)
  • Know what went wrong and where
  • Create own conditions using regular expressions for example
  • Create own validators which contain a collection of conditions
  • Support iOS, macOS, and tvOS

Dependencies

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate FormValidatorSwift into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.3'
use_frameworks!

pod 'FormValidatorSwift', '~> 3.0'

Then, run the following command:

$ pod install

Manually

If you prefer not to use either of the aforementioned dependency managers, you can integrate FormValidatorSwift into your project manually.

Embedded Framework

  • Open up Terminal, cd into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:
$ git init
  • Add FormValidatorSwift as a git submodule by running the following command:
$ git submodule add https://github.com/ustwo/formvalidator-swift.git
  • Open the new FormValidatorSwift folder, and drag the FormValidatorSwift.xcodeproj into the Project Navigator of your application's Xcode project.

    It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Select the FormValidatorSwift.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.

  • In the tab bar at the top of that window, open the "General" panel.

  • Click on the + button under the "Embedded Binaries" section.

  • You will see two different FormValidatorSwift.xcodeproj folders each with two different versions of the FormValidatorSwift.framework nested inside a Products folder.

    It does not matter which Products folder you choose from, but it does matter whether you choose the top or bottom FormValidatorSwift.framework.

  • Select the top FormValidatorSwift.framework for iOS, the middle one for tvOS, or the bottom one for macOS.

    You can verify which one you selected by inspecting the build log for your project. The build target for FormValidatorSwift will be listed as FormValidatorSwift iOS, FormValidatorSwift macOS, or FormValidatorSwift tvOS.

  • And that's it!

The FormValidatorSwift.framework is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.


Usage

The two core components of FormValidatorSwift are Condition and Validator. These are both protocols, with many common implementations provided by the framework.

A Condition defines a specific requirement for a String to be considered valid and defines a way to check the String. A Validator defines a way to check whether a String is valid based on a set of Condition. These provide the building blocks upon which the other elements of FormValidatorSwift are built.

ValidatorTextField and ValidatorTextView provide common UI implementations for a validatable text input method. These controls can then be combined into a Form for quick validation of all text input.

Condition

A Condition is typically defined by a regular expression. This is used in the default implementation to check the string. However, you can provide your own implementation of the check(text:) function to do a more complicated validation.

Here is an example using one of the built-in conditions. Note that calling check(text:) simply returns a Bool as to whether the text is valid or not.

let condition = AlphanumericCondition()

let validResult = condition.check("Foo123")
let invalidResult = condition.check("Foo?!@")

Validator

A Validator takes an array of Condition and checks each condition to validate a string. If the validation fails, then checkConditions(text:) will return an array of the violated conditions.

Here is an example using one of the built-in validators. In this example, validResult will be nil and invalidResult will be [AlphanumericCondition].

let validator = AlphanumericValidator()

let validResult = validator.checkConditions("Foo123")
let invalidResult = validator.checkConditions("Foo?!@")

ValidatorTextField

To provide a user interface, you can use ValidatorTextField or ValidatorTextView. These are subclasses of UITextField and UITextView respectively (or NSTextField and NSTextView on macOS). They both conform to the ValidatorControl protocol, which has the additional capability of using a Validator to check the text.

Here is an example of a text field that would only allow alphanumeric text.

let nameTextField = ValidatorTextField(validator: AlphanumericValidator())

This does not work well for more complicated text fields. For example, you would not want an email address validated until the user is finished typing. To postpone validation, we need to set shouldAllowViolation and validateOnFocusLossOnly both to be true. Example:

let emailTextField = ValidatorTextField(validator: EmailValidator())
emailTextField.shouldAllowViolation = true
emailTextField.validateOnFocusLossOnly = true

We can respond to changes in the validity of ValidatorTextField by implementing the ValidatorControlDelegate and setting ourselves as the validator delegate (using the setValidatorDelegate(_:) method). Below is an example implementation. In the example we highlight the text field with a red border if it is invalid. We also list the error in a label called errorLabel and present it to the user.

func validatorControl(validatorControl: ValidatorControl, changedValidState validState: Bool) {
    guard let controlView = validatorControl as? UIView else {
        return
    }

    if validState {
        controlView.layer.borderColor = nil
        controlView.layer.borderWidth = 0.0
        errorLabel.hidden = true
    } else {
        controlView.layer.borderColor = UIColor.red.CGColor
        controlView.layer.borderWidth = 2.0
    }
}

func validatorControl(validatorControl: ValidatorControl, violatedConditions conditions: [Condition]) {
    var errorText = ""
    for condition in conditions {
        errorText += condition.localizedViolationString
    }
    errorLabel.text = errorText

    errorLabel.hidden = false
}

func validatorControlDidChange(validatorControl: ValidatorControl) {
    // Not used in this example
}

Form

We can combine a series of ValidatorControl into a Form. We have a convenience implementation call ControlForm. We can then combine our alphanumeric textfield and our email textfield from our previous examples into a form. This provides an easy method for checking if the entire form is valid (say, before submission of the form data to a server). Below is an example:

var form = ControlForm()

form.addEntry(nameTextField)
form.addEntry(emailTextField)

if form.isValid {
  // Hooray! Our form is valid. Submit the data!
  ...
} else {
  // Sad day, we need to have the user fix the data.
  ...
}

Example

More detailed examples can be found in the iOS Example and macOS Example apps in this repository.

Collaborate

We welcome contributors! Whether you're fixing a typo, squashing a bug, or adding new functionality please join us in making this project better. Read our contributing guidelines to find out how to add your support.

Maintainers

  • Shagun Madhikarmi (@madhikarma)
  • Aaron McTavish (@aamctustwo)

Contact

License

FormValidatorSwift is released under the MIT License. See the LICENSE file.

More Repositories

1

ustwo.com-frontend

The New & Improved ustwo Website
JavaScript
1,818
star
2

US2FormValidator

Form validation framework for iOS.
Objective-C
593
star
3

mastermind

Man in the middle testing
Python
385
star
4

clockwise

Watch face framework for Android Wear developed by ustwo
Java
345
star
5

videoplayback-ios

Swift AVPlayer wrapper using the VIPER architecture. Currently a work in progress
Swift
218
star
6

autocluster

The code base around the cluster prototypes.
JavaScript
101
star
7

ReplayKitUnityBridge

A bridge created from iOS to Unity - exposing the Cocoa ReplayKit API. It allows you to record the screen, set a limited time for the screen to be recorded, and receive a file of the recorded session
ASP
61
star
8

vip-demo-swift

Swift sample app demonstrating VIP architecture for iOS.
Swift
49
star
9

android-boilerplate

Android Boilerplate à la ustwo
Java
42
star
10

docker-browser-sync

Docker image for BrowserSync
JavaScript
39
star
11

vip-templates-swift

Xcode templates based on https://clean-swift.com for generating Swift source code in View Interactor Presenter architecture.
Shell
32
star
12

bdd-crossplatform-apps

An ustwo guide about one way to BDD cross platform applications.
Ruby
27
star
13

clockwise-samples

Sample watch faces
Java
24
star
14

GL-2D-watchface

A light-weight library to manage and render Bitmaps in OpenGL on a watch face.
Java
20
star
15

objective-c-style-guide

The ustwo Objective-C style guide
20
star
16

US2MapperKit

JSON driven object mapper developed by ustwo
Swift
17
star
17

midi-to-philips-hue

This is a proof of concept of a set of Philips Hue lights controlled by a Behringer BCD300 MIDI controller
Ruby
16
star
18

android-coding-standards

Android Coding Standards
16
star
19

daydream-experiment

Google Daydream Experiment
C#
15
star
20

recipe-book

ustwobies love food, so they Open Source their recipes, as any sane geek would do.
15
star
21

docker-node-boilerplate

⚠️ No longer maintained ⚠️
JavaScript
10
star
22

brunel

A demonstration of organisation for an app that runs on both iOS and tvOS platforms using a unified code base. ⚠️ No longer maintained ⚠️
Swift
9
star
23

docker-sauce-connect

Builds a Sauce Labs Connect image
Makefile
9
star
24

photoshop-contrast-checker

JavaScript
8
star
25

baseviewcontroller-swift

An organizational tool for writing custom view controllers using UIKit.
Ruby
8
star
26

branded-interactions

JavaScript
7
star
27

react-native-experiment

React Native experiment for mapping of content
JavaScript
7
star
28

scout

Scout discovers apps installed on an iOS device utilising the URL scheme feature.
Objective-C
7
star
29

ibeacon-demo

Objective-C
6
star
30

US2KeyboardType

Objective-C
5
star
31

ustwoadventure

Front-end code for the Adventure website
JavaScript
5
star
32

autolayout-helper-ios

UIView helper to easily create common Auto Layout Constraints for iOS
Objective-C
4
star
33

image-color-swift

Swift
4
star
34

toolbar-keyboard-ios

UIToolbar extension to create toolbars useful for keyboards or pickers for iOS
Objective-C
4
star
35

mockingbird

A demonstration of using the Swift Package Manager and writing Swift code to run on both Linux and macOS.
Swift
3
star
36

array-remove-swift

Swift
2
star
37

xcode-snippets

Xcode Snippets
2
star
38

mongolabkit-swift

MongoLabKit is a REST client API for iOS, tvOS and watchOS written to make REST calls to a MongoLab database.
Swift
2
star
39

github-scanner

A commandline tool for scanning GitHub repositories. ⚠️ No longer maintained ⚠️
Swift
2
star
40

bench-xr-social-experiments

C#
1
star
41

ustwo-swiftui-bindings-example

Swift
1
star
42

google-docs-scripts

A collection of Google docs scripts
JavaScript
1
star
43

UIColor-US2Colors

UIColor+US2Colors category
Objective-C
1
star
44

homebrew-tools

Collection of tools ustwo development might need
Ruby
1
star
45

ios-swift-dictionaries-sample

Sample code from "Reading from a Dictionary in Swift" blog post.
Objective-C
1
star
46

docker-ansible

DEPRECATED
Makefile
1
star
47

pink-workshop-22

JavaScript
1
star
48

docker-nodejs

DEPRECATED
Makefile
1
star
49

baseview-swift

UIView subclass to abstract Base functionality for iOS
Swift
1
star
50

github-issues

A command line interface to fetch Github Issues ⚠️ No longer maintained ⚠️
Rust
1
star
51

engineering-blog

usTwo Engineering
SCSS
1
star