Question

I have a string coming from server and want to check whether it contains expressions like phone numbers, mail address and email. I got success in case of phone number and mail address, but not email. I am using NSDataDetector for this purpose. eg

NSString *string = sourceNode.label; //coming from server

//Phone number
NSDataDetector *phoneDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:nil]; 
NSArray *phoneMatches = [phoneDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in phoneMatches) {

    if ([match resultType] == NSTextCheckingTypePhoneNumber) {
        NSString *matchingStringPhone = [match description];
        NSLog(@"found URL: %@", matchingStringPhone);
    }
}  

But how to do the same for email?

Was it helpful?

Solution

In apple documentation, it seems that recognised types does not include email : http://developer.apple.com/library/IOs/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html#//apple_ref/c/tdef/NSTextCheckingType

So I suggest you to use a Regexp. It would be like :

NSString* pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+";

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
if ([predicate evaluateWithObject:@"johndoe@example.com"] == YES) {
  // Okay
} else {
  // Not found
}

EDIT :

Because @dunforget got the best solution despites mine is the accepted one, please read his answer.

OTHER TIPS

if (result.resultType == NSTextCheckingTypeLink)
{
    if ([result.URL.scheme.locaseString isEqualToString:@"mailto"])
    {
        // email link
    }
    else
    {
        // url
    }
}

Email address falls into NSTextCheckingTypeLink. Simply look for "mailto:" in the URL found and you will know it is an email or URL.

Try following code, see if it works for you :

NSString * mail = so@so.com
NSDataDetector * dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSTextCheckingResult * firstMatch = [dataDetector firstMatchInString:mail options:0 range:NSMakeRange(0, [mail length])];
BOOL result = [firstMatch.URL isKindOfClass:[NSURL class]] && [firstMatch.URL.scheme isEqualToString:@"mailto"];

Here's a clean Swift version.

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 Version:

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

It seems detector now works for email?

let types = [NSTextCheckingType.Link, NSTextCheckingType.PhoneNumber] as NSTextCheckingType
responseAttributedLabel.enabledTextCheckingTypes = types.rawValue

And I am able to click on emails. I am using the TTTAttributedLabel though.

Here's an email example in Swift 1.2. Might not check all edge cases, but it's a good place to start.

func isEmail(emailString : String)->Bool {

    // need optional - will be nil if successful
    var error : NSError?

    // use countElements() with Swift 1.1
    var textRange = NSMakeRange(0, count(emailString))

    // Link type includes email (mailto)
    var detector : NSDataDetector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: &error)!

    if error == nil {

    // options value is ignored for this method, but still required! 
    var result = detector.firstMatchInString(emailString, options: NSMatchingOptions.Anchored, range: textRange)

        if result != nil {

            // check range to make sure a substring was not detected
            return result!.URL!.scheme! == "mailto" && (result!.range.location == textRange.location) && (result!.range.length == textRange.length)

        }

    } else {

        // handle error
    }

    return false
}

let validEmail = isEmail("someone@site.com") // returns true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top