DevC
DevC

Reputation: 7022

Email Validation in iOS - Regex not working - code contains Array of valid email addresses

I have an array of supposedly valid emails, Im testing my regex statement to check if my regex method works. Based on this list, they should all return through, however some dont, how would I bullet proof my code so it works accordingly:

+(BOOL)isValidEmail: (NSString *)emailString{
    BOOL stricterFilter = YES;
    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 *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailString];

}

The array of valid emails is:

 NSArray *array = [NSArray arrayWithObjects:@"[email protected]",

                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"email@[123.123.123.123]",
                  @"“email”@example.com",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  @"[email protected]",
                  nil];

I then perform this loop:

for (NSString * email in array) {
    NSLog(@"Email: %@ is valid %@",email,[NSString isValidEmail:email] ? @"YES" : @"NO");
    ;
}

Which logs:

 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid NO
 Email: email@[123.123.123.123] is valid NO
 Email: /“email/”@example.com is valid NO
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES
 Email: [email protected] is valid NO
 Email: [email protected] is valid YES
 Email: [email protected] is valid YES

They should all be valid according to this Valid email addresses

Upvotes: 0

Views: 95

Answers (1)

depperm
depperm

Reputation: 10746

Try this:

[\da-zA-Z_+\\.\-\/(“|”)]+@(([a-zA-Z\-]+(\\.[a-zA-Z]+){1,2})|(\[?[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\]?))

Upvotes: 1

Related Questions