- Notifications
You must be signed in to change notification settings - Fork33
A framework to validate inputs of text fields and text views in a convenient way.
License
ustwo/formvalidator-swift
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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 atustwo.
- Simply use
ValidatorTextField
instead ofUITextField
orNSTextField
(ValidatorTextView
instead ofUITextView
orNSTextView
) - 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
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 yourPodfile
:
source'https://github.com/CocoaPods/Specs.git'platform:ios,'8.3'use_frameworks!pod'FormValidatorSwift','~> 3.0'
Then, run the following command:
$ pod install
If you prefer not to use either of the aforementioned dependency managers, you can integrate FormValidatorSwift into your project manually.
- 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 gitsubmodule by running the following command:
$ git submodule add https://github.com/ustwo/formvalidator-swift.git
Open the new
FormValidatorSwift
folder, and drag theFormValidatorSwift.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 theFormValidatorSwift.framework
nested inside aProducts
folder.It does not matter which
Products
folder you choose from, but it does matter whether you choose the top or bottomFormValidatorSwift.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 asFormValidatorSwift iOS
,FormValidatorSwift macOS
, orFormValidatorSwift 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.
The two core components of FormValidatorSwift areCondition
andValidator
. These are both protocols, with many common implementations provided by the framework.
ACondition
defines a specific requirement for aString
to be considered valid and defines a way to check theString
. AValidator
defines a way to check whether aString
is valid based on a set ofCondition
. These provide the building blocks upon which the other elements of FormValidatorSwift are built.
ValidatorTextField
andValidatorTextView
provide common UI implementations for a validatable text input method. These controls can then be combined into aForm
for quick validation of all text input.
ACondition
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 thecheck(text:)
function to do a more complicated validation.
Here is an example using one of the built-in conditions. Note that callingcheck(text:)
simply returns aBool
as to whether the text is valid or not.
letcondition=AlphanumericCondition()letvalidResult= condition.check("Foo123")letinvalidResult= condition.check("Foo?!@")
AValidator
takes an array ofCondition
and checks each condition to validate a string. If the validation fails, thencheckConditions(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 benil
andinvalidResult
will be[AlphanumericCondition]
.
letvalidator=AlphanumericValidator()letvalidResult= validator.checkConditions("Foo123")letinvalidResult= validator.checkConditions("Foo?!@")
To provide a user interface, you can useValidatorTextField
orValidatorTextView
. These are subclasses ofUITextField
andUITextView
respectively (orNSTextField
andNSTextView
on macOS). They both conform to theValidatorControl
protocol, which has the additional capability of using aValidator
to check the text.
Here is an example of a text field that would only allow alphanumeric text.
letnameTextField=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 setshouldAllowViolation
andvalidateOnFocusLossOnly
both to betrue
. Example:
letemailTextField=ValidatorTextField(validator:EmailValidator())emailTextField.shouldAllowViolation=trueemailTextField.validateOnFocusLossOnly=true
We can respond to changes in the validity ofValidatorTextField
by implementing theValidatorControlDelegate
and setting ourselves as the validator delegate (using thesetValidatorDelegate(_:)
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 callederrorLabel
and present it to the user.
func validatorControl(validatorControl:ValidatorControl, changedValidState validState:Bool){guardlet controlView= validatorControlas?UIViewelse{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]){varerrorText=""forconditionin conditions{ errorText+= condition.localizedViolationString} errorLabel.text= errorText errorLabel.hidden=false}func validatorControlDidChange(validatorControl:ValidatorControl){ // Not used in this example}
We can combine a series ofValidatorControl
into aForm
. We have a convenience implementation callControlForm
. 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:
varform=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....}
More detailed examples can be found in theiOS Example
andmacOS Example
apps in this repository.
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 ourcontributing guidelines to find out how to add your support.
- Shagun Madhikarmi (@madhikarma)
- Aaron McTavish (@aamctustwo)
FormValidatorSwift is released under the MIT License. See the LICENSE file.
About
A framework to validate inputs of text fields and text views in a convenient way.
Topics
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors6
Uh oh!
There was an error while loading.Please reload this page.