Last active
November 16, 2017 10:54
-
-
Save olbartek/6c9a86c48f50c849dd4da77d82e1a931 to your computer and use it in GitHub Desktop.
Text validation proposal
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
protocol TextValidating { | |
func validateText(_ text: String) throws | |
} | |
class PasswordValidator: TextValidating { | |
let minimumAllowedCharacters = 6 | |
enum Error: Swift.Error, CustomStringConvertible { | |
case passwordTooShort | |
var description: String { | |
switch self { | |
case .passwordTooShort: return "Password is to short." | |
} | |
} | |
var localizedInfo: String { | |
switch self { | |
case .passwordTooShort: return "short.password".localized | |
} | |
} | |
} | |
func validateText(_ text: String) throws { | |
if text.characters.count < minimumAllowedCharacters { | |
throw Error.passwordTooShort | |
} | |
} | |
} | |
class UsernameValidator: TextValidating { | |
let allowedCharacterSet: CharacterSet | |
private lazy var notAllowedCharacterSet = self.allowedCharacterSet.inverted | |
let minimumAllowedCharacters = 4 | |
let maximumAllowedCharacters = 15 | |
enum Error: Swift.Error, CustomStringConvertible { | |
case invalidCharacterSet | |
case usernameTooShort | |
case usernameTooLong | |
var description: String { | |
switch self { | |
case .invalidCharacterSet: return "Username contains invalid characters." | |
case .usernameTooShort: return "Username is to short." | |
case .usernameTooLong: return "Username is to long." | |
} | |
} | |
var localizedInfo: String { | |
switch self { | |
case .invalidCharacterSet: return "UsernameValidator.invalidCharacterSet".localized | |
case .usernameTooShort: return "UsernameValidator.usernameToShort".localized | |
case .usernameTooLong: return "UsernameValidator.usernameToLong".localized | |
} | |
} | |
} | |
init(allowedCharacterSet: CharacterSet = .alphanumerics) { | |
self.allowedCharacterSet = allowedCharacterSet | |
} | |
func validateText(_ text: String) throws { | |
if !containsOnlyAllowedCharacters(text) { | |
throw Error.invalidCharacterSet | |
} else if text.characters.count < minimumAllowedCharacters { | |
throw Error.usernameTooShort | |
} else if text.characters.count > maximumAllowedCharacters { | |
throw Error.usernameTooLong | |
} | |
} | |
private func containsOnlyAllowedCharacters(_ text: String) -> Bool { | |
let textWithAllowedCharacters = text.components(separatedBy: notAllowedCharacterSet).joined(separator: "") | |
return text == textWithAllowedCharacters | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment