Kishon Daniels
Kishon Daniels

Reputation: 55

Confirm email address exists and is not already taken, using Parse and email Regex

I am at the part of my register process where I would like to confirm if the email given by the user exists and is not already taken.

So far, I have the regex set and customized to how I want it (I am limiting the user to a student email address).

- (BOOL)validateEmail:(NSString *)emailStr {
NSString *emailRegex = @"[A-Za-z]+\\.[A-Za-z]+@[ace]+\\.[tamut]+\\.[edu]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

[self checkEmailAndDisplayAlert];

return [emailTest evaluateWithObject:emailStr];

}

I throw an alert if the email is not acceptable.

 - (void)checkEmailAndDisplayAlert {

if(![self validateEmail:[_email text]]) {

     [self.email becomeFirstResponder];

    // user entered invalid email address
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];


} else {
    // user entered valid email address
    [self registerNewUser];
  }
}

If I enter an email that does not meet the regex requirements, the proper alert is not shown, and I am still allowed to pass through the registration as a new user. What am I doing wrong?

Please don't hold back on any feedback, I am new to programming and this is something I need to know, no excuses.

Upvotes: 0

Views: 167

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

In your validateEmail method, you call checkEmailAndDisplayAlert ([self checkEmailAndDisplayAlert];), and it also calls validateEmail. I'd delete [self checkEmailAndDisplayAlert]; to avoid endless loops.

Also, try changing the regex to

NSString *emailRegex = @"^[A-Za-z]+\\.[A-Za-z]+@ace\\.tamut\\.edu$";

The function to check validity could also look like:

- (BOOL)validateEmail:(NSString *)emailStr
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-z]+\\.[a-z]+@ace\\.tamut\\.edu$" options:NSRegularExpressionCaseInsensitive error:&error];

    NSAssert(regex, @"Unable to create regular expression");

    NSRange txtRng = NSMakeRange(0, emailStr.length);
    NSRange matchRng = [regex rangeOfFirstMatchInString:emailStr options:NSMatchingReportProgress range:txtRng];

    BOOL validated = NO;

    if (matchRng.location != NSNotFound)
        validated = YES; // Match found

    return validated;
}

^ and $ are added at the beginning anf end of the regex pattern to enable whole string search.

Upvotes: 1

Related Questions