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:
- File → New → File… or use ⌘N.
- Select Objective-C File.
- Type in category name, select File Type: Category, and then select the base class.
- 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