Pages

Subscribe:

Thursday, September 22, 2011

Email address validation in a text field

// This function will return either TRUE or FALSE depending on the validity of a given email address
-(BOOL) validateEmail: (NSString *) candidate {
NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:candidate];
}

// Implement the UITextFieldDelegate in the .h file
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(textField == txtEmail)
{
if([self validateEmail:textField.text])
[textField resignFirstResponder];
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Please enter a valid email address." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return NO;
}
}
return YES;
}

2 comments:

Unknown said...

thanks friend is working fine

Unknown said...

Its not working...it doesn't enter into the loop

Post a Comment