Вот чистая версия Swift.
extension String {
func isValidEmail() -> Bool {
guard !self.lowercaseString.hasPrefix("mailto:") else { return false }
guard let emailDetector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue) else { return false }
let matches = emailDetector.matchesInString(self, options: NSMatchingOptions.Anchored, range: NSRange(location: 0, length: self.characters.count))
guard matches.count == 1 else { return false }
return matches[0].URL?.absoluteString == "mailto:\(self)"
}
}
Версия Swift 3.0:
extension String {
func isValidEmail() -> Bool {
guard !self.lowercased().hasPrefix("mailto:") else { return false }
guard let emailDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return false }
let matches = emailDetector.matches(in: self, options: NSRegularExpression.MatchingOptions.anchored, range: NSRange(location: 0, length: self.characters.count))
guard matches.count == 1 else { return false }
return matches[0].url?.absoluteString == "mailto:\(self)"
}
}
Objective-C:
@implementation NSString (EmailValidator)
- (BOOL)isValidEmail {
if ([self.lowercaseString hasPrefix:@"mailto:"]) { return NO; }
NSDataDetector* dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
if (dataDetector == nil) { return NO; }
NSArray* matches = [dataDetector matchesInString:self options:NSMatchingAnchored range:NSMakeRange(0, [self length])];
if (matches.count != 1) { return NO; }
NSTextCheckingResult* match = [matches firstObject];
return match.resultType == NSTextCheckingTypeLink && [match.URL.absoluteString isEqualToString:[NSString stringWithFormat:@"mailto:%@", self]];
}
@end