I improved @Azik answer. I allow more special characters which are allowed by guidelines, as well as return a few extra edge cases as invalid.
The group think going on here to only allow ._%+-
in the local part is not correct per guidelines. See @Anton Gogolev answer on this question or see below:
The local-part of the email address may use any of these ASCII characters:
uppercase and lowercase Latin letters
A
toZ
anda
toz
;digits
0
to9
;special characters
!#$%&'*+-/=?^_`{|}~
;dot
.
, provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g.[email protected]
is not allowed but"John..Doe"@example.com
is allowed);space and
"(),:;<>@[\]
characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash); comments are allowedwith parentheses at either end of the local-part; e.g.
john.smith(comment)@example.com
and(comment)[email protected]
are both equivalent to[email protected]
;
The code I use will not allow restricted out of place special characters, but will allow many more options than the majority of answers here. I would prefer more relaxed validation to error on the side of caution.
if enteredText.contains("..") || enteredText.contains("@@")
|| enteredText.hasPrefix(".") || enteredText.hasSuffix(".con"){
return false
}
let emailFormat = "[A-Z0-9a-z.!#$%&'*+-/=?^_`{|}~]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPredicate = NSPredicate(format:"SELF MATCHES %@", emailFormat)
return emailPredicate.evaluate(with: enteredText)