Last active
September 20, 2017 14:55
-
-
Save RPallas92/04b10618b23b8975ff8a1205c1a47142 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
//Check if the password is long enough | |
func isPasswordLongEnough(_ password:String) -> Validation<[String], String> { | |
if password.characters.count < 8 { | |
return Validation.Failure(["Password must have more than 8 characters."]) | |
} else { | |
return Validation.Success(password) | |
} | |
} | |
//Check if the password contains a special character | |
func isPasswordStrongEnough(_ password:String) -> Validation<[String], String> { | |
if (password.range(of:"[\\W]", options: .regularExpression) != nil){ | |
return Validation.Success(password) | |
} else { | |
return Validation.Failure(["Password must contain a special character."]) | |
} | |
} | |
//Check if the user is different from password, by Jlopez | |
func isDifferentUserPass(_ user:String, _ password:String) -> Validation<[String], String> { | |
if (user == password){ | |
return Validation.Failure(["Username and password MUST be different."]) | |
} else { | |
return Validation.Success(password) | |
} | |
} | |
//Concating all validations in one that checks all rules | |
func isPasswordValid(user: String, password:String) -> Validation<[String], String> { | |
return isPasswordLongEnough(password) | |
.sconcat(isPasswordStrongEnough(password)) | |
.sconcat(isDifferentUserPass(user, password)) | |
} | |
//Examples with invalid password | |
let result = isPasswordValid(user: "Richi", password: "Richi") | |
/* ▿ Validation<Array<String>, String> | |
▿ Failure : 3 elements | |
- 0 : "Password must have more than 8 characters." | |
- 1 : "Password must contain a special character." | |
- 2 : "Username and password MUST be different." | |
*/ | |
//Example with valid password | |
let result = isPasswordValid(user:"Richi", password: "Ricardo$") | |
/* | |
▿ Validation<Array<String>, String> | |
- Success : "Ricardo$" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment