I use this code to check if text fields are empty or not. The first time, it will work, but when I change the text field values, the alert does not works.
-(void)sendclick {
NSString *msg;
if(firstnametextfield.text==NULL) {
msg=@"enter first name";
NSLog(@"%@",firstnametextfield.text);
}
else if(lastnametextfield.text==NULL) {
msg=@"enter last name";
NSLog(@"%@",lastnametextfield.text);
}
else if(emailtextfield.text==NULL) {
msg=@"enter email address";
NSLog(@"%@",emailtextfield.text);
}
else if(companytextfield.text==NULL) {
msg=@"enter company name";
NSLog(@"%@",companytextfield.text);
}
else if(phonetextfield.text==NULL) {
msg=@"enter phone numper";
NSLog(@"%@",phonetextfield.text);
}
else {
msg=@"register success fully";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}
}
There are a couple of things to consider about this code:
As others have pointed out, this is not the correct way to check for an empty string.
a. First, if you do want to check for a string that is not allocated, you should be checking for
niland notNULL.b. Secondly, the string could also be allocated, but have no characters, so you should check to see if it is an empty string as well.
c. Note that you typically want to check BOTH of those conditions, and do the same thing, because, usually, there is no difference between a string that is nil and one that is empty as far as the business logic is concerned.
d. The easiest way to do this is to simply check the
lengthof the string. This works, because if a message is sent to anilobject, it will return 0, and if it is an actual string with no characters, it will also return 0.Therefore, a check similar to this would work instead:
You typically do not want to check the value of a text field directly like this for form validation. This is because, under certain situations (like when a text field is in a table view cell and scrolls off of the screen) the text field is not available and you won’t have access to the data stored in the text field.
Instead, you should collect the text immediately after it is entered by setting the delegate of the text field to your view controller and implementing the following function:
Then, when you are ready to validate the entered information, check the values that you have stored instead of the actual text field values themselves, using the technique from #1 above.