How to validate email with RegEx and Obj-C

Discussion in 'Mac Programming' started by ace2600, May 5, 2008.

  1. ace2600 macrumors member

    Mar 16, 2008
    Austin, Texas
    This was my first time doing regular expressions with objective-c. I did not find much out there on regex email validations for objective-c, so figured I'd post my simple example to help anyone out later.
    NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@"emailRegEx];
    //Valid email address
    if ([emailTest evaluateWithObject:detail] == YES)
    { ... }
    //Invalid email address
    { ... }
    NSPredicate can do a lot more than just regex on a string too. Please let me know if there are better options.
  2. sujithkrishnan macrumors 6502

    May 9, 2008
    What about iPhone dev?? NSPredicate wont work with iPhoneOS , right?
  3. savar macrumors 68000


    Jun 6, 2003
    District of Columbia
    Regex and e-mail addresses don't mix.
  4. iSee macrumors 68040


    Oct 25, 2004
    LOL. Nice!

    To be fair, that regular expression is for validating addresses in email headers. The OPs expression is close for the dot-atom form of an addr-spec address--pretty much what people mean when they ask you to type, write, or otherwise give you their email address. IMHO, it's acceptable to validate an email address entered in to a form, for example.

    Except that some valid characters are missing... looking up RFC...
    Other valid characters are:


    I've seen $ and ! used in real addresses before, but I don't recall ever seeing the others.

    Oh yeah, the RFC you probably want to refer to is 2822:

Share This Page