On a form, I'm using -[UITextFieldDelegate textFieldDidEndEditing]:
to register any errors and store them in a NSMutableArray
instance variable formErrors
.
I'll use formErrors
when my submit button is pressed, or perhaps to disable the button disabled while there are errors on the form.
Error messages get put on formErrors
like this:
-(void)textFieldDidEndEditing:(UITextField *)textField
{
if ( textField == [self nameField] ) {
if ( ([[textField text] length] < 2) || ([[textField text] length] > 20) ) {
[[formErrors addObject:@"Name must contain a minimum of 2 and a maximum of 20 characters only."];
} else {
if ([[textField text] rangeOfCharacterFromSet:alphaSet].location != NSNotFound) {
[[formErrors addObject:@"Name must contain letters and spaces only."];
}
}
}
}
I'm trying to figure out the best way to get the formErrors objects stored so they can be accessed after all fields have been checked.
What has worked for me is to declare an instance var:
{
NSMutableArray *formErrors;
}
Then initialise in viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
formErrors = [[NSMutableArray alloc] init];
Then in prepareForSegue:
I have some temporary code to check things are working:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
int errCount = [formErrors count];
// check if all textfield values are filled in if not then disallow form submit
for (NSString *error in formErrors) {
NSLog(@"Total %d errors, \n Error Message: %@", errCount, error);
}
This feels wrong for some reason. Should I be declaring a property instead? All I want to do is, as I enter and leave fields, check if there are any errors; if there are, just store the error message in formErrors
, so I can do what I need to do in the prepareForSegue:
.
I notice I get slightly confused when dealing with these types of scenarios.