I am developing a register functionality in my app. I have some UITextFields
like Email, password, username, first name.... and I want to validate them before I make the request to the server with the information. Now I validate them when I close the keypad doing this:
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
if (textField == emailTextField)
{
if(emailTextField.text.length > 5){
if(![self validateEmailWithString:emailTextField.text])
{
// 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];
return NO;
//email.text=@"";
} else {
[self.emailDelegate sendEmailForCell:emailTextField.text];
[textField resignFirstResponder];
return YES;
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Email address too Short" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
return NO;
}
}
return YES;
}
- (BOOL) validateEmailWithString:(NSString *)emailStr
{
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:emailStr];
}
But, when I do not close the keyPad with textFieldShouldReturn
method I can not validate the UITextField
where I am typing. I mean, when I click on the next UITextField
before I press return key in the keypad I can type in the next UITextField
and textFieldShouldReturn
never has been called.
So, I guess I should use this method - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
but I do not want to show to the user that it is an invalid email(or pass, or whatever) every time he types a letter.
So, my question is How could I manage this validation when the user stops typing letters in the keyboard but before he close the keypad?
Another question. Could I store in a variable the Boolean of this method shouldChangeCharactersInRange
?
Thank you