Skip to content

Instantly share code, notes, and snippets.

@RPallas92
Created September 24, 2017 11:34
Show Gist options
  • Save RPallas92/f4c54c3171dcf630077c007760b8d10f to your computer and use it in GitHub Desktop.
Save RPallas92/f4c54c3171dcf630077c007760b8d10f to your computer and use it in GitHub Desktop.
//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"))
}
//Is password valid is a more complex validation created by combining minLenght and matches validations
let result = isPasswordValid("A")
/* Validation<Array<String>, String>
▿ Failure : 2 elements
- 0 : "Password must contain an special character"
- 1 : "Password must have more than 8 characters"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment