167

What is the cleanest way to validate an email address that a user enters on iOS 2.0?

NOTE: This is a historical question that is specific to iOS 2.0 and due to its age and how many other questions are linked to it it cannot be retired and MUST NOT be changed to a "modern" question.

8
  • I am looking for a cocoa solution. I understand the validity of emails and the rules around validating emails. However since RegEx is not easily accessible on Cocoa Touch, I am looking for a Cocoa Touch solution to validation. Not a list of the rules around validation. Apr 28, 2009 at 23:30
  • So far the best code suggestion I have found is using RegExKitLite and regular expressions. Fortunately it is less painful than it sounds. Apr 29, 2009 at 14:31
  • See comments below about using NSRegularExpression for apps not supporting os < 4.0.
    – beOn
    Feb 27, 2011 at 19:59
  • 1
    Since this seems to be the canonical question regarding email address validation, it makes sense to update with improved answers as iOS matures. With that in mind, I've added an answer which uses iOS's NSDataDetector to validate email addresses: stackoverflow.com/a/23547905/257550
    – memmons
    May 8, 2014 at 16:53
  • 2
    This question appears to be off-topic because it is about iOS 2.0 which was deprecated years ago. May 20, 2014 at 16:57

13 Answers 13

354

The answer to Using a regular expression to validate an email address explains in great detail that the grammar specified in RFC 5322 is too complicated for primitive regular expressions.

I recommend a real parser approach like MKEmailAddress.

As quick regular expressions solution see this modification of DHValidation:

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex]; 

    return [emailTest evaluateWithObject:candidate];
}
14
  • 9
    Great but doesn't work on OS <3.0, because NSPredicate is not available.
    – Felixyz
    Oct 13, 2009 at 12:58
  • 4
    Nice. Everyone forgets that NSPredicate can run regexps.
    – Rog
    Oct 14, 2009 at 11:57
  • 5
    That is one very bad regexp. For instance, it will fail on people using the .museum top domain. Refer to this article: linuxjournal.com/article/9585
    – Jonny
    Aug 27, 2010 at 4:13
  • 18
    There's a more complete regex at cocoawithlove.com/2009/06/… that can be used instead of this simple one. Sep 1, 2010 at 22:49
  • 12
    Here is a very naive but liberal email regex as a Cocoa string: @"[^@]+@[^.@]+(\\.[^.@]+)+" If you need to verify an email address send a message to it and see if it succeeds. You will never verify it with any level of accuracy with a regex alone, so it's best not to piss of users and lose sign ups because of an unnecessarily strict regex. Sep 13, 2011 at 16:35
20

Read the RFC. Almost everyone that thinks they know how to parse/clean/validate an email address is wrong.

https://www.rfc-editor.org/rfc/rfc2822 Section 3.4.1 is very useful. Notice

dtext           =       NO-WS-CTL /     ; Non white space controls

                        %d33-90 /       ; The rest of the US-ASCII
                        %d94-126        ;  characters not including "[",
                                        ;  "]", or "\"

Yes, that means +, ', etc are all legit.

1
17

The best solution I have found so far (and the one I ended up going with) is to add RegexKitLite To the project which gives access to regular expressions via NSString Categories.

It is quite painless to add to the project and once in place, any of the regular expression email validation logic will work.

7
  • 5
    NSPredicate can do RegEx without adding additional libraries to your project.
    – BadPirate
    Sep 3, 2010 at 17:54
  • 10
    This question, from April of 2009 was before NSPredicate existed on iOS. Sep 3, 2010 at 20:02
  • 7
    Again, NSRegularExpression DID NOT EXIST in iOS 2.0 when this question was asked. Mar 6, 2011 at 19:46
  • 9
    @Marcus, the point of Stack Overflow is not to maintain a historical record of how particular problems were solved in the past. That said, I've edited your question to emphasize the 2.0 compatibility angle.
    – benzado
    May 22, 2011 at 20:43
  • 2
    Please read the title, this is for iOS 2.0 which Catlan's solution did not exist. Dec 2, 2012 at 21:42
10

A good start is to decide what do you and do you not want to accept as an email address?

99% of of email addresses look like this: [email protected] or [email protected]

However, it's technically legal to have an email address like this: f!#$%&'*+-/=?^_{|}~"ha!"@com

There are probably only a handful of valid emails in the world for top-level domains, and almost nobody uses most of those other characters (especially quotes and backticks), so you might want to assume that these are all invalid things to do. But you should do so as a conscious decision.

Beyond that, do what Paul says and try to match the input to a regular expression like this: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$

That one will match pretty much everybody's email address.

2
  • even though this answer was written in 2009 it still comes up very high in search results. i just wanted to add that this is no longer up to date and the above regex is a bit restrictive. for example, now you can have 4 digit or more top level domain
    – Jack
    Aug 6, 2015 at 19:49
  • Good point, edited it to "at least 2 digits". Feel free to edit further if you like. Aug 6, 2015 at 19:57
7

While the focus on regular expressions is good, but this is only a first and necessary step. There are other steps that also need to be accounted for a good validation strategy.

Two things on top of my head are :

  1. DNS validation to make sure the domain actually exists.

  2. After dns validation, you can also choose to do an smtp validation. send a call to the smtp server to see if the user actually exists.

In this way you can catch all kinds of user errors and make sure it is a valid email.

7

This function is simple and yet checks email address more thoroughly. For example, according to RFC2822 an email address must not contain two periods in a row, such as [email protected]

It is also important to use anchors in regular expressions as seen in this function. Without anchors the following email address is considered valid: first;name)[email protected](blah because the [email protected] section is valid, ignoring first;name) at the beginning and (blah at the end. Anchors force the regular expressions engine to validate the entire email.

This function uses NSPredicate which does not exist in iOS 2. Unfortunately it may not help the asker, but hopefully will help others with newer versions of iOS. The regular expressions in this function can still be applied to RegExKitLite in iOS 2 though. And for those using iOS 4 or later, these regular expressions can be implemented with NSRegularExpression.

- (BOOL)isValidEmail:(NSString *)email
{
    NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
    NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
    NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
}

See validate email address using regular expression in Objective-C.

2
  • iOS 2.0 did not have NSPredicate. Oct 15, 2013 at 1:37
  • 2
    But what is the use of this question and what is the use of ios 2. We are having latest os that is ios 7.1. you can also use ios 6. May 20, 2014 at 5:48
6
NSString *emailString = textField.text; **// storing the entered email in a string.** 
**// Regular expression to checl the email format.** 
NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailReg]; 
if (([emailTest evaluateWithObject:emailString] != YES) || [emailStringisEqualToString:@""]) 
{ 
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:@" Enter Email in" message:@"[email protected] format" delegate:self 
cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

enter code here

[loginalert show]; 
[loginalert release]; 
} 
If email is invalid, it will remind the user with an alert box. 
Hope this might be helpful for you all. 
0
4

I have found that using a regular expression works quite well to validate an email address.

The major downside to regular expressions of course is maintainability, so comment like you have never commented before. I promise you, if you don't you will wish you did when you go back to the expression after a few weeks.

Here is a link to a good source, http://www.regular-expressions.info/email.html.

2
  • I implemented the second-last one on that page recently, and I'm quite happy with it. It works fine for a simple [email protected] email address, with no quotes or brackets for a full name. Works great for web form validation where people won't be typing that sort of thing in anyway.
    – zombat
    Apr 28, 2009 at 23:05
  • 2
    Poor people with their .museum TLD.
    – BadPirate
    Sep 3, 2010 at 17:53
3

Digging up the dirt, but I just stumbled upon SHEmailValidator which does a perfect job and has a nice interface.

2
  • This question was specific to iOS 2.0 which did not have NSPredicate or a whole host of other things that are being used in that library. Nov 15, 2013 at 19:22
  • 1
    I know, but I landed here first while searching "ios email validation". Maybe some future me will perform the same search and land here and it'll save him some time.
    – Cyrille
    Nov 16, 2013 at 18:19
1

Many web sites provide RegExes but you'd do well to learn and understand them as well as verify that what you want it to do meets your needs within the official RFC for email address formats.

For learning RegEx, interpreted languages can be a great simplifier and testbed. Rubular is built on Ruby, but is a good quick way to test and verify: http://www.rubular.com/

Beyond that, buy the latest edition of the O'Reilly book Mastering Regular Expressions. You'll want to spend the time to understand the first 3 or 4 chapters. Everything after that will be building expertise on highly optimized RegEx usage.

Often a series of smaller, easier to manage RegExes are easier to maintain and debug.

0

Here is an extension of String that validates an email in Swift.

extension String {

    func isValidEmail() -> Bool {
        let stricterFilter = false
        let stricterFilterString = "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"
        let laxString = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
        let emailRegex = stricterFilter ? stricterFilterString : laxString
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: self)
    }
}

Copied from the answer to: Check that an email address is valid on iOS

1
  • There was no NSPredicate on iOS 2.0 Feb 16, 2017 at 22:51
-2

You shouldn't try to use regex to validate an email. With ever changing TLDs, your validator is either incomplete or inaccurate. Instead, you should leverage Apple's NSDataDetector libraries which will take a string and try to see if there are any known data fields (emails, addresses, dates, etc). Apple's SDK will do the heavy lifting of keeping up to date with TLDs and you can piggyback off of their efforts!! :)

Plus, if iMessage (or any other text field) doesn't think it's an email, should you consider an email?

I put this function in a NSString category, so the string you're testing is self.

- (BOOL)isValidEmail {
    // Trim whitespace first
    NSString *trimmedText = [self stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
    if (self && self.length > 0) return NO;

    NSError *error = nil;
    NSDataDetector *dataDetector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:&error];
    if (!dataDetector) return NO;

    // This string is a valid email only if iOS detects a mailto link out of the full string
    NSArray<NSTextCheckingResult *> *allMatches = [dataDetector matchesInString:trimmedText options:kNilOptions range:NSMakeRange(0, trimmedText.length)];
    if (error) return NO;
    return (allMatches.count == 1 && [[[allMatches.firstObject URL] absoluteString] isEqual:[NSString stringWithFormat:@"mailto:%@", self]]);
}

or as a swift String extension

extension String {
    func isValidEmail() -> Bool {
        let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty, let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return false
        }
        let allMatches = dataDetector.matches(in: trimmed, options: [], range: NSMakeRange(0, trimmed.characters.count))

        return allMatches.count == 1 && allMatches.first?.url?.absoluteString == "mailto:\(trimmed)"
    }
}
4
  • 1
    This question is from EIGHT years ago. Sep 6, 2017 at 1:21
  • 1
    And yet, if you Google validate email objective-c, this question is the third result. Some things on the internet do not age. :-)
    – Craig Otis
    Sep 6, 2017 at 10:41
  • 1
    Please stop spamming links to this answer below every post you can find that is related to validating email addresses. Comments are for requesting clarification, not for spamming links to your answers.
    – user229044
    Sep 9, 2017 at 16:16
  • BTW, NSDataDetector did NOT exist in iOS 2.0 which is what this question was/is about. Sep 13, 2017 at 15:47
-7
// Method Call
NSString *email = @"Your Email string..";

BOOL temp = [self validateEmail:email];

if(temp)
{
// Valid
}
else
{
// Not Valid
}
// Method description

- (BOOL) validateEmail: (NSString *) email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isValid = [emailTest evaluateWithObject:email];
    return isValid;
}
2
  • 3
    This thread/question is for iOS 2. NSPredicate did not exist in iOS 2; it was not added until iOS 3. May 19, 2014 at 19:48
  • 3
    I replied because your answer is wrong. The question is "how do you do X on iOS Y" and you answered with a framework that does not exist on that version of iOS. May 21, 2014 at 15:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.