Kunal Kumar
Kunal Kumar

Reputation: 1722

how to show textfield validation error message in a label

I am a beginner in iOS programming. I am creating a registration form, and doing client side validation on the textfield. What I want is to display the error message below the textfield in a label. I searched alot and get this so question but I am finding it difficult to understand and I think there must be a simpler way to achieve this. I am able to show the message in a label, but the problem is it doesn't hide when the focus is set to that textfield again.

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField == _emailTextField)
    {
        if(![self validateEmailWithString:_emailTextField.text])
        {
            //showing error on a label
            [_errorMessageLabel setText:@"please enter valid Email"];
        }
    }
    else
    {
        //valid email
    }
}

- (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];
}

Upvotes: 4

Views: 6768

Answers (2)

Bhanupriya
Bhanupriya

Reputation: 1202

Yes, there is a simple solution. Just hide your label when focus is set to UITextField in below delegate method

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    _errorMessageLabel.hidden = YES;

    ...

}

Upvotes: 3

Pepeng Hapon
Pepeng Hapon

Reputation: 377

Correct me if I'm wrong, what you only want is to hide the text (meaning empty text) or hide the label itself?

To hide text, use "textFieldDidBeginEditing" to empty your label

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    [_errorMessageLabel setText:@""];
}

To hide the label,

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    _errorMessageLabel.hidden = YES;
}

Upvotes: 2

Related Questions