Created
May 5, 2014 12:25
-
-
Save cmlenz/8ef4ebdab696fc24335e to your computer and use it in GitHub Desktop.
Using the data detector API for email validation. Still probably uses regular expression under the covers (NSDataDetector is a NSRegularExpression subclass), but at least uses a system method instead of a hand-coded regex pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (BOOL)isValidEmailAddress:(NSString *)text | |
{ | |
NSError *error = NULL; | |
NSRange textRange = {0, [text length]}; | |
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error]; | |
if (!detector) { | |
NSLog(@"Could not instantiate link detector for email validation: %@", error); | |
return NO; | |
} | |
NSTextCheckingResult *result = [detector firstMatchInString:text options:0 range:textRange]; | |
if (![result.URL.scheme isEqual:@"mailto"]) { | |
// No link was detected, or it wasn't an email address | |
return NO; | |
} | |
if (result.range.location > textRange.location || result.range.length < textRange.length) { | |
// The detected email address does't span the entire input text | |
return NO; | |
} | |
return YES; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://gist.github.com/anonymous/3bea53c05336f931bd1d for tests and results.