- Notifications
You must be signed in to change notification settings - Fork38
SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations.
License
andresinaka/SwiftCop
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
SwiftCop is a validation library fully written in Swift and inspired by the clarity ofRuby On Rails Active Record validations.
Build a standard drop-in library for validations in Swift while making it easily extensible for users to create custom validations. And avoid developers from writing over and over again the same code and validations for different projects.
- Quick validations.
- Super simple and declarative syntax.
- Easily extensible.
- Fully Swift 4.0
SwiftCop was built around three different concepts:
Trial
is anEnum
that implements theTrialProtocol
publicprotocolTrialProtocol{func trial()->((_ evidence:String)->Bool)}
We can useTrial
to quickly validatestrings
.SwiftCop
ships with a very fully featuredTrial
implementation. The following trials are provided:
This validates that the attributes are not included in the evidence string.
letexclusionTrial=Trial.exclusion([".com",".ar",".uy"])lettrial= exclusionTrial.trial()XCTAssertFalse(trial("http://www.nytimes.com"))XCTAssertFalse(trial("http://www.lanacion.com.ar"))XCTAssertTrue(trial("http://www.elpais.es"))
This validates whether the evidence matches a given regular expression.
letformatTrial=Trial.format("^#([a-f0-9]{6}|[a-f0-9]{3})$") // hexa number with #lettrial= formatTrial.trial()XCTAssertTrue(trial("#57b5b5"))XCTAssertFalse(trial("57b5b5"))XCTAssertFalse(trial("#h7b5b5"))
This validates that the attributes are included in the evidence string.
letinclusionTrial=Trial.inclusion([".com",".ar",".uy"])lettrial= inclusionTrial.trial()XCTAssertTrue(trial("http://www.nytimes.com"))XCTAssertTrue(trial("http://www.lanacion.com.ar"))XCTAssertFalse(trial("http://www.elpais.es"))
This validates whether the evidence is an email or not.
letemailTrial=Trial.emaillettrial= emailTrial.trial()XCTAssertTrue(trial("test@test.com"))
This validates the length of given evidence:
letlengthTrial=Trial.Length(.Is,10)lettrial= lengthTrial.trial()XCTAssertTrue(trial("0123456789"))
letlengthTrial=Trial.Length(.Minimum,10)lettrial= lengthTrial.trial()XCTAssertTrue(trial("0123456789"))
letlengthTrial=Trial.Length(.Maximum,10)lettrial= lengthTrial.trial()XCTAssertTrue(trial("0123456789"))
letinterval=Trial.Length(.In,2..<5asHalfOpenInterval)lettrial= interval.trial()XCTAssertTrue(trial("1234"))
letinterval=Trial.Length(.In,2...5asClosedInterval)lettrial= interval.trial()XCTAssertFalse(trial("123456"))
TheSuspect
is aStruct
that is the glue between some other concepts always used while validating fields. It puts together aUITextField
that is going to be the source of theevidence
, asentence
that is going to be the text shown if thesuspect
is guilty (when theTrial
returns false) and theTrial
itself, that can be a custom made trial for the suspect or you can use one of the trials provided by the library:
Suspect(view: UITextField, sentence: String, trial: TrialProtocol)Suspect(view: UITextField, sentence: String, trial:(String)-> Bool)
We can check if theSuspect
is guilty or not with:
func isGuilty() -> Bool
This method is going to returntrue
if theTrial
returnsfalse
.
Also we can directly ask for theverdict
on theSuspect
, this is going to check if it's guilty or not and then return and empty string (""
) or thesentence
.
For example:
letsuspect=Suspect(view:self.dummyTextField, sentence:"Invalid email", trial:.Email)letverdict= suspect.verdict() // this can be "" or "Invalid Email"
Finally we have the guy that is going to enforce the validations! The cop is going to get all the suspects together and give us the tools to check who are the guilty suspects or if there is any guilty suspect at all.
As you can imagine this is going to add a suspect under the vigilance of a cop, we can add as many suspects as we want:
openfunc addSuspect(_ suspect:Suspect)
This will let us check if there is any guilty suspect between all the suspects under the surveillance of our cop:
publicfunc anyGuilty()->Bool
This will let us know all the guilty suspects our cop found:
publicfunc allGuilties()->Array<Suspect>
This will let us check if a UITextField that is suspect is guilty or not:
publicfunc isGuilty(textField:UITextField)->Suspect?
The example is shipped in the repository:
classViewController:UIViewController{@IBOutlet weakvarvalidationLabel:UILabel!@IBOutlet weakvarfullNameMessage:UILabel!@IBOutlet weakvaremailMessage:UILabel!@IBOutlet weakvarpasswordMessage:UILabel!@IBOutlet weakvarfullName:UITextField!@IBOutlet weakvaremailTextField:UITextField!@IBOutlet weakvarpassword:UITextField!letswiftCop=SwiftCop()overridefunc viewDidLoad(){super.viewDidLoad()swiftCop.addSuspect(Suspect(view:self.fullName, sentence:"More Than Two Words Needed"){return $0.components(separatedBy:"").filter{$0!=""}.count>=2})swiftCop.addSuspect(Suspect(view:self.emailTextField, sentence:"Invalid email", trial:Trial.email))swiftCop.addSuspect(Suspect(view:self.password, sentence:"Minimum 4 Characters", trial:Trial.length(.minimum,4)))}@IBActionfunc validateFullName(_ sender:UITextField){self.fullNameMessage.text= swiftCop.isGuilty(sender)?.verdict()}@IBActionfunc validateEmail(_ sender:UITextField){self.emailMessage.text= swiftCop.isGuilty(sender)?.verdict()}@IBActionfunc validatePassword(_ sender:UITextField){self.passwordMessage.text= swiftCop.isGuilty(sender)?.verdict()}@IBActionfunc allValid(_ sender:UITextField){letnonGultiesMessage="Everything fine!"letallGuiltiesMessage= swiftCop.allGuilties().map{return $0.sentence}.joined(separator:"\n")self.validationLabel.text= allGuiltiesMessage.characters.count>0? allGuiltiesMessage: nonGultiesMessage}@IBActionfunc hideKeyboard(_ sender:AnyObject){self.view.endEditing(true)}}
You can just clone the repo and copy theSwiftCop
folder to your project or you can use one of the following options:
Setting up withCocoaPods
pod 'SwiftCop'
Then:
import SwiftCop
And you are all set!
Setting up withCarthage
- TODO
About
SwiftCop is a validation library fully written in Swift and inspired by the clarity of Ruby On Rails Active Record validations.