You shouldn't try to use regex to validate an email. With ever changing TLDs, your validator is either incomplete or inaccurate. Instead, you should leverage Apple's NSDataDetector
libraries which will take a string and try to see if there are any known data fields (emails, addresses, dates, etc). Apple's SDK will do the heavy lifting of keeping up to date with TLDs and you can piggyback off of their efforts!! :)
Plus, if iMessage (or any other text field) doesn't think it's an email, should you consider an email?
I put this function in a NSString
category, so the string you're testing is self
.
- (BOOL)isValidEmail {
// Trim whitespace first
NSString *trimmedText = [self stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
if (self && self.length > 0) return NO;
NSError *error = nil;
NSDataDetector *dataDetector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:&error];
if (!dataDetector) return NO;
// This string is a valid email only if iOS detects a mailto link out of the full string
NSArray<NSTextCheckingResult *> *allMatches = [dataDetector matchesInString:trimmedText options:kNilOptions range:NSMakeRange(0, trimmedText.length)];
if (error) return NO;
return (allMatches.count == 1 && [[[allMatches.firstObject URL] absoluteString] isEqual:[NSString stringWithFormat:@"mailto:%@", self]]);
}
or as a swift String
extension
extension String {
func isValidEmail() -> Bool {
let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return false
}
let allMatches = dataDetector.matches(in: trimmed, options: [], range: NSMakeRange(0, trimmed.characters.count))
return allMatches.count == 1 && allMatches.first?.url?.absoluteString == "mailto:\(trimmed)"
}
}