Created
May 5, 2014 15:33
-
-
Save anonymous/3bea53c05336f931bd1d to your computer and use it in GitHub Desktop.
Test email address validation with esoteric email addresses
This file contains hidden or 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; | |
} | |
- (void)testEmail:(NSString *)text isValid:(BOOL)isValid { | |
BOOL result = [self isValidEmailAddress:text]; | |
if (result != isValid) NSLog(@"%@ should be %@", text, isValid ? @"valid" : @"invalid"); | |
} | |
- (void)testEmails { | |
[self testEmail:@"NotAnEmail" isValid:NO]; | |
[self testEmail:@"@NotAnEmail" isValid:NO]; | |
[self testEmail:@"\"test\\\\blah\"@example.com" isValid:YES]; | |
[self testEmail:@"\"test\\blah\"@example.com" isValid:NO]; | |
[self testEmail:@"\"test\\\rblah\"@example.com" isValid:YES]; | |
[self testEmail:@"\"test\rblah\"@example.com" isValid:NO]; | |
[self testEmail:@"\"test\\\"blah\"@example.com" isValid:YES]; | |
[self testEmail:@"\"test\"blah\"@example.com" isValid:NO]; | |
[self testEmail:@"customer/[email protected]" isValid:YES]; | |
[self testEmail:@"[email protected]" isValid:YES]; | |
[self testEmail:@"!def!xyz%[email protected]" isValid:YES]; | |
[self testEmail:@"[email protected]" isValid:YES]; | |
[self testEmail:@"[email protected]" isValid:YES]; | |
[self testEmail:@"[email protected]" isValid:NO]; | |
[self testEmail:@"[email protected]" isValid:NO]; | |
[self testEmail:@"[email protected]" isValid:NO]; | |
[self testEmail:@"[email protected]" isValid:NO]; | |
[self testEmail:@"\"Austin@Powers\"@example.com" isValid:YES]; | |
[self testEmail:@"[email protected]" isValid:YES]; | |
[self testEmail:@"\"Ima.Fool\"@example.com" isValid:YES]; | |
[self testEmail:@"\"Ima Fool\"@example.com" isValid:YES]; | |
[self testEmail:@"Ima [email protected]" isValid:NO]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results:
11 of 22 failed.