Question

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.

Was it helpful?

Solution 3

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.

OTHER TIPS

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];
}

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

http://tools.ietf.org/html/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.

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: bob.smith@foo.com or fred@bla.edu

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.

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.

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 firstname..lastname@domain..com

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)lastname@domain.com(blah because the lastname@domain.com 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.

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:@"abc@example.com 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. 

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.

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

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.

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

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)"
    }
}
// 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top