How to validate email with RegEx and Obj-C

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

  1. ace2600 macrumors member

    Joined:
    Mar 16, 2008
    Location:
    Austin, Texas
    #1
    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.
    PHP:
    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
    else
    { ... }
    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

    Joined:
    May 9, 2008
    Location:
    Bangalore
    #2
    What about iPhone dev?? NSPredicate wont work with iPhoneOS , right?
     
  3. savar macrumors 68000

    savar

    Joined:
    Jun 6, 2003
    Location:
    District of Columbia
    #3
    Regex and e-mail addresses don't mix.
    http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
     
  4. iSee macrumors 68040

    iSee

    Joined:
    Oct 25, 2004
    #4
    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: http://tools.ietf.org/html/rfc2822#section-3.4
     

Share This Page