Skip to content

Instantly share code, notes, and snippets.

@darthpelo
Last active February 2, 2020 14:24
Show Gist options
  • Save darthpelo/25170bc5f628fab4144468530f56f3db to your computer and use it in GitHub Desktop.
Save darthpelo/25170bc5f628fab4144468530f56f3db to your computer and use it in GitHub Desktop.
An example regarding how Swift 5.1 Property Wrapper can be useful for a light Input Validation enforcement.
@propertyWrapper
struct EmailValidated {
private(set) var defaultValue: String = ""
var wrappedValue: String {
get { defaultValue }
set { defaultValue = maxLength(newValue) && isValid(newValue)
?
newValue
:
"" }
}
init(wrappedValue initialValue: String) {
self.wrappedValue = initialValue
}
private func isValid(emailAddress: String) -> Bool {
let emailRegEx = "(?:[a-zA-Z0-9!#$%\\&‘*+/=?\\^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%\\&'*+/=?\\^_`{|}"
+ "~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
+ "x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
+ "z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
+ "]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
+ "9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
+ "-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
let emailValidation = NSPredicate(format:"SELF MATCHES[c] %@", emailRegEx)
return emailValidation.evaluate(with: emailAddress)
}
private func maxLength(_ emailAddress: String) -> Bool {
guard emailAddress.count <= 80 else {
return false
}
guard let domainKey = emailAddress.firstIndex(of: "@") else { return false }
return emailAddress[..<domainKey].count <= 64
}
}
struct User {
@EmailValidated var email: String
var name: String
}
let validUser = User(email: "aasd@gmail.com", name: "Darthpelo")
let invalidUser = User(email: "sdf[]@gmail.com", name: "Darthpelo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment