Something that every app developer has to deal with at some point or another is string validation, with the most common problem being email validation. That is because every single online service has a login or signup view controller. It is so common you almost wonder why Apple and every single other language developer doesn’t have a built in version.

Below I have shared a very simple email validation method using NSPredicate.  You can use this method to create a new NSString’s Category file and have this method available anywhere in your app directly from any NSString object.

Email Validation Check in Objective C source code

-(BOOL)isValidEmail : (NSString*)emailAddress
{
    BOOL stricterFilter = NO;
    NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
    NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailPredicate evaluateWithObject:emailAddress];
}

To create a new Category using Objective C and Xcode 6 or greater NSString+EmailValidation.m/.h:

  1. File → New → File… or use ⌘N.
  2. Select Objective-C File. newcategorystep1
  3. Type in category name, select File Type: Category, and then select the base class. newcategorystep2
  4. Complete the flow to create the new category and make sure to save your files in a Categories group folder to keep things organized.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s