Reputation: 58087
What is the value of a UITextField when it is empty? I can't seem to get this right.
I've tried (where `phraseBox' it the name of the said UITextField
if(phraseBox.text != @""){
and
if(phraseBox.text != nil){
What am I missing?
Upvotes: 3
Views: 12546
Reputation: 1
Validation against empty UITextfield. if you don't want that UITextField should not accept blank white spaces. Use this code snippet:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
if ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound) {
return YES;
} else {
return NO;
}
}
Upvotes: 0
Reputation: 131
found this at apple discussions when searching for the same thing,thought ill post it here too. check the length of the string :
NSString *value = textField.text;
if([value length] == 0) {
}
or optionally trim whitespaces from it before validation,so user cannot enter spaces instead.works well for usernames.
NSString *value = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if([value length] == 0) {
// Alert the user they forgot something
}
Upvotes: 13
Reputation: 332
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *fullText = [textField.text stringByAppendingString:string];
if ((range.location == 0) && [self isABackSpace:string]) {
//the textFiled will be empty
}
return YES;
}
-(BOOL)isABackSpace:(NSString*)string {
NSString* check =@"Check";
check = [check stringByAppendingString:string];
if ([check isEqualToString:@"Check"]) {
return YES;
}
return NO;
}
Upvotes: 1
Reputation: 3630
Actually, I ran into slight problems using Raphael's approach with multiple text fields. Here's what I came up with:
if ((usernameTextField.text.length > 0) && (passwordTextField.text.length > 0)) {
loginButton.enabled = YES;
} else {
loginButton.enabled = NO;
}
Upvotes: 0
Reputation: 1145
Use for text field validation:
-(BOOL)validation{
if ([emailtextfield.text length] <= 0) {
[UIAlertView showAlertViewWithTitle:AlertTitle message:AlertWhenemailblank];
return NO; }
return YES;}
Upvotes: 0
Reputation: 506
Try following code
textField.text is a string value so we are checking it like this
if([txtPhraseBox.text isEqualToString:@""])
{
// There's no text in the box.
}
else
{
NSLog(@"Text Field Text == : %@ ",txtPhraseBox.text);
}
Upvotes: 1
Reputation: 7846
// Check to see if it's blank
if([phraseBox.text isEqualToString:@""]) {
// There's no text in the box.
}
// Check to see if it's NOT blank
if(![phraseBox.text isEqualToString:@""]) {
// There's text in the box.
}
Upvotes: 21