Guest User

Untitled

a guest
Nov 18th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. protocol TextValidating {
  2. func validateText(_ text: String) throws
  3. }
  4.  
  5. class PasswordValidator: TextValidating {
  6. let minimumAllowedCharacters = 6
  7.  
  8. enum Error: Swift.Error, CustomStringConvertible {
  9. case passwordTooShort
  10.  
  11. var description: String {
  12. switch self {
  13. case .passwordTooShort: return "Password is to short."
  14. }
  15. }
  16.  
  17. var localizedInfo: String {
  18. switch self {
  19. case .passwordTooShort: return "short.password".localized
  20. }
  21. }
  22. }
  23.  
  24. func validateText(_ text: String) throws {
  25. if text.characters.count < minimumAllowedCharacters {
  26. throw Error.passwordTooShort
  27. }
  28. }
  29. }
  30.  
  31. class UsernameValidator: TextValidating {
  32. let allowedCharacterSet: CharacterSet
  33. private lazy var notAllowedCharacterSet = self.allowedCharacterSet.inverted
  34. let minimumAllowedCharacters = 4
  35. let maximumAllowedCharacters = 15
  36.  
  37. enum Error: Swift.Error, CustomStringConvertible {
  38. case invalidCharacterSet
  39. case usernameTooShort
  40. case usernameTooLong
  41.  
  42. var description: String {
  43. switch self {
  44. case .invalidCharacterSet: return "Username contains invalid characters."
  45. case .usernameTooShort: return "Username is to short."
  46. case .usernameTooLong: return "Username is to long."
  47. }
  48. }
  49.  
  50. var localizedInfo: String {
  51. switch self {
  52. case .invalidCharacterSet: return "UsernameValidator.invalidCharacterSet".localized
  53. case .usernameTooShort: return "UsernameValidator.usernameToShort".localized
  54. case .usernameTooLong: return "UsernameValidator.usernameToLong".localized
  55. }
  56. }
  57. }
  58.  
  59. init(allowedCharacterSet: CharacterSet = .alphanumerics) {
  60. self.allowedCharacterSet = allowedCharacterSet
  61. }
  62.  
  63. func validateText(_ text: String) throws {
  64. if !containsOnlyAllowedCharacters(text) {
  65. throw Error.invalidCharacterSet
  66. } else if text.characters.count < minimumAllowedCharacters {
  67. throw Error.usernameTooShort
  68. } else if text.characters.count > maximumAllowedCharacters {
  69. throw Error.usernameTooLong
  70. }
  71. }
  72.  
  73. private func containsOnlyAllowedCharacters(_ text: String) -> Bool {
  74. let textWithAllowedCharacters = text.components(separatedBy: notAllowedCharacterSet).joined(separator: "")
  75. return text == textWithAllowedCharacters
  76. }
  77. }
Add Comment
Please, Sign In to add comment