Iam Wayne
Iam Wayne

Reputation: 561

Check if UITextfield is empty and display alert

I want to prevent data from being saved and present an alert if any of the text fields are left empty. This is what I have, the alert pops up when I hit the save button, but the textfields are still saving with blank text when empty.

   // check if text feild is empty

    if usernameLabel.text == "" || passwordLabel.text == "" || phoneNumber.text == "" || service.text == "" || address.text == ""  {

        // Alert
        let optionMenu = UIAlertController(title: nil, message: "Please Enter Text", preferredStyle: .Alert)

        // Add actions to the menu
        let cancelAction = UIAlertAction(title: "Ok", style: .Cancel, handler:
            nil)
        optionMenu.addAction(cancelAction)

        // Display the menu
        self.presentViewController(optionMenu, animated: true, completion: nil)

    }


}   //End save button

Upvotes: 0

Views: 1832

Answers (3)

Ashish Ramani
Ashish Ramani

Reputation: 1214

if(usernameLabel.text.characters.count == 0 || passwordLabel.text.characters.count == 0 || phoneNumber.text.characters.count == 0 || service.text.characters.count == 0 || address.text.characters.count == 0)  
{ 
    // your code 
    return
}

Use .characters.count for checking is checking textfield is blank or not.

Upvotes: 1

vaibby
vaibby

Reputation: 1275

after your if end add return like this

if usernameLabel.text.length == 0 || passwordLabel.text.length == 0 || phoneNumber.text.length == 0 || service.text.length == 0 || address.text.length == 0  { 

    // your code 
    return
}

Upvotes: 1

S. Karthik
S. Karthik

Reputation: 618

you first remove the whitspace first because it also consider as character. So must remove whitespace use below code,

-(NSString *)remove_whitespace:(NSString *)string_data /* Remove whitspace in the string */
{
      NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
      string_data = [string_data stringByTrimmingCharactersInSet:whitespace];
      return string_data;
}

then , count the length of string. if it is greater than 0 go on, else popup error like below,

if([self remove_whitespace:textstring])
{
NSLog(@"work");
  }
else
{
NSLog(@"so error");
}

Got it?

Upvotes: 1

Related Questions