Tuesday 9 June 2015

How to check if the email is valid in iOS sdk

Many apps require email validation in iOS. Here the function that can be used to check if email string is valid or not. It can be achieved by NSPredicate like following:
  1. -(BOOL)isValidEmail:(NSString *)checkString
  2. {
  3. long numberOfAtPieces = [[checkString componentsSeparatedByString:@"@"] count];
  4. if (numberOfAtPieces > 2){
  5. return NO;
  6. }
  7. BOOL stricterFilter = NO;
  8. NSString *stricterFilterString = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
  9. NSString *laxString = @".+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*";
  10. NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  11. NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  12. return [emailTest evaluateWithObject:checkString];
  13. }
Just past the checkString as email you want to validate and it returns 'YES' if email is valid else returns 'NO'.


For such more Blogs you can visit to http://findnerd.com/NerdDigest

No comments:

Post a Comment