Last active
September 24, 2017 11:04
-
-
Save RPallas92/47eb57540b120212a680cd2722482343 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Validate min length | |
func minLength(_ value:String, min:Int, fieldName:String) -> Validation<[String], String>{ | |
if(value.characters.count < min){ | |
return Validation.Failure(["\(fieldName) must have more than \(min) characters"]) | |
} else { | |
return Validation.Success(value) | |
} | |
} | |
//Validate match a regular expression | |
func matches(_ value:String, regex:String, errorMessage:String) -> Validation<[String], String>{ | |
if(value.range(of:regex, options: .regularExpression) == nil){ | |
return Validation.Failure([errorMessage]) | |
} else { | |
return Validation.Success(value) | |
} | |
} | |
//Validate password: concatenation of matches and minLength | |
func isPasswordValid(_ password:String) -> Validation<[String], String> { | |
return matches(password, regex: "[\\W]", errorMessage: "Password must contain an special character") | |
.sconcat(minLength(password, min: 8, fieldName: "Password")) | |
} | |
//Validate name: minLength | |
func isNameValid(_ name: String) -> Validation<[String], String> { | |
return minLength(name, min: 3, fieldName: "Name") | |
} | |
//Validate form: concatenation of isPasswordValid and isNameValid | |
func validateForm(name: String, password: String) -> Validation<[String], String> { | |
return isNameValid(name) | |
.sconcat(isPasswordValid(password)) | |
} | |
//Examples | |
let result = validateForm(name: "FP", password: "Ricardo$") | |
/*▿ Validation<Array<String>, String> | |
▿ Failure : 1 element | |
- 0 : "Name must have more than 3 characters" | |
*/ | |
let result1 = validateForm(name: "FP", password: "A") | |
/* Validation<Array<String>, String> | |
▿ Failure : 3 elements | |
- 0 : "Name must have more than 3 characters" | |
- 1 : "Password must contain an special character" | |
- 2 : "Password must have more than 8 characters" | |
*/ | |
let result2 = validateForm(name: "FPZ", password: "A") | |
/* ▿ Validation<Array<String>, String> | |
▿ Failure : 2 elements | |
- 0 : "Password must contain an special character" | |
- 1 : "Password must have more than 8 characters" | |
*/ | |
let result3 = validateForm(name: "FPZ", password: "A$k34k21!!") | |
/* ▿ Validation<Array<String>, String> | |
- Success : "A$k34k21!!" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment