Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if UITextFields are empty?

I have a bunch of UITextFields where a user must enter a number (the keyboard is the number pad) before pressing a submit button. When the submit button is pressed, a "check" method is called that wants to check if the data is valid... aka not empty. Now this would be easy if it was just one textField but I have 14. I want a simple if-statement that checks if one of the fields or all of the fields are empty....

I have the follow UITextFields declared: number1, number2, number3 etc etc and I have the follow strings declared which can take the value of the UITextField.text... they are declared: temp1, temp2, temp3 etc...

how would I go about making a pseudocode if statement like the one below?

Thanks

 if (!valid)
 {

NSLog (@"not valid)
} 

 else
{
 //proceed to next method
}
like image 897
Teddy13 Avatar asked Jan 26 '12 09:01

Teddy13


4 Answers

I am supposing UITextField variable as *tfield so here is the solution

if (tfield.text.length > 0 || tfield.text != nil || ![tfield.text isEqual:@""])
{
   //do your work
}
else
{
   //through error
}
like image 101
Assad Ullah Avatar answered Sep 29 '22 15:09

Assad Ullah


or you could just call

[myTextField hasText];

which will return NO if the field is empty.

like image 25
AmirZ Avatar answered Sep 29 '22 16:09

AmirZ


I think something like this is what you want. It's just using isEqualToString: to check if the string is empty.

NSString *temp1 = number1.text;
NSString *temp2 = number2.text;
... ///< temp3, etc

if ([temp1 isEqualToString:@""]) {
    // temp1 not valid
} else if ([temp2 isEqualToString:@""]) {
    // temp2 not valid
} ... {
    // temp3, etc
} else {
    // Valid
}

You may want to trim whitespace characters when grabbing temp1 so that @" " would also be blank. For that, take a look at NSString's stringByTrimmingCharactersInSet: method like so:

NSString *temp1 = [number1.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

Update:

If you want to do it with an array you could do something like:

NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
[array addObject:number1.text];
[array addObject:number2.text];
... ///< number3, etc

BOOL ok = YES;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if ([obj isEqualToString:@""]) {
        ok = NO;
        *stop = YES;
    }
}];

if (ok) {
    // Valid
} else {
    // Not valid
}
like image 24
mattjgalloway Avatar answered Sep 29 '22 16:09

mattjgalloway


Something like this would iterate through your UITextFields:

[self.view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  if ([obj isKindOfClass:[UITextField class]]) {
     // do your checks
  }
}];
like image 42
ksh Avatar answered Sep 29 '22 16:09

ksh