Roberto C Dl Garza
Roberto C Dl Garza

Reputation: 84

Shows the Alert when UITextField's are full or empty Swift

Below is the code in that if the userNameTF or the passwordTF are full or empty it shows the alert.

@IBAction func LoginBtn(sender: AnyObject) {
    let userName = userNameTF.text
    let password = passwordTF.text    

    if ((userName?.isEmpty) != nil) {

        displayMyAlertMessage ("Forget to fill your user name")
        return        
    }

    if ((password?.isEmpty) != nil){

        displayMyAlertMessage ("Forget to fill your password")
        return    
    }        
}

func displayMyAlertMessage(userMessage:String){

    let myAlert = UIAlertController(title: "WOF", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)  
    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
    myAlert.addAction(okAction)
    self.presentViewController(myAlert, animated: true, completion: nil)
 }

Upvotes: 0

Views: 2233

Answers (2)

vadian
vadian

Reputation: 285079

That's a good example to use guard

@IBAction func LoginBtn(sender: AnyObject) {

   guard let userName = userNameTF.text where !userName.isEmpty else {
        displayMyAlertMessage ("Forget to fill your user name")
        return
   }

   guard let password = passwordTF.text where !password.isEmpty else {
        displayMyAlertMessage ("Forget to fill your password")
        return
   }

    // do something with userName and password
}

Upvotes: 2

Pavan Gandhi
Pavan Gandhi

Reputation: 1749

You can simply check your code with my code. there is minor mistake u did for checking value is empty or not.

follow below steps :

1.) Define IBOutlet for textfield

@IBOutlet var userNameTF : UITextField!
@IBOutlet var passwordTF : UITextField!

2.) Write below code on button clicked Event.

    let userName = userNameTF.text
    let password = passwordTF.text

    if (userName!.isEmpty) 
    {
        displayMyAlertMessage ("Forget to fill your user name")
        return
    }
    else if (password!.isEmpty)
    {
        displayMyAlertMessage ("Forget to fill your password")
        return
    }
    else
    {
        // Do Whatever u want.
    }

Enjoy coding...its work fine.

Upvotes: 3

Related Questions