Skip to content

Instantly share code, notes, and snippets.

@cmlenz
Created May 5, 2014 12:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmlenz/8ef4ebdab696fc24335e to your computer and use it in GitHub Desktop.
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.
- (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;
}
@cmlenz
Copy link
Author

cmlenz commented May 5, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment