Aparna
Aparna

Reputation: 57

Validating Textfield in iOS

I am trying to validate my credentials(username and password). For some reason the code never enters into the first if loop even when I leave the username and password field empty and click on the Login button. Attaching the code and a screenshot as well. Can someone help me fix this.?

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var NameField: UITextField!
    @IBOutlet weak var PasswordField: UITextField!

    @IBAction func textFieldDoneEditing(sender: UITextField){
        sender.resignFirstResponder()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
       // let stringkey = NSUserDefaults.standardUserDefaults()
       // NameField.text = stringkey.stringForKey("savedusername")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func LogIn(sender: AnyObject) {
        //let myText  = NameField.text;
        //NSUserDefaults.standardUserDefaults().setObject(myText, forKey: "savedusername")
        //NSUserDefaults.standardUserDefaults().synchronize()
        if(NameField == "" || PasswordField == "")
        {
            let alert = UIAlertController(title: nil , message: "Invalid Credentials!", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }

        if(NameField != ""  && PasswordField != ""){
            let alert = UIAlertController(title: nil , message: "Login Successfull", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

enter image description here

Upvotes: 0

Views: 607

Answers (3)

KKRocks
KKRocks

Reputation: 8322

In swift below code through we can check textfield empty or not.

if textfield.text?.characters.count == 0 {
    print("Empty")
}else {
    print("Not Empty")
}

Upvotes: 0

siburb
siburb

Reputation: 5017

You're comparing the UITextField to "" rather than its text property.

Try NameField.text etc instead.

Upvotes: 1

Hitesh Surani
Hitesh Surani

Reputation: 13577

You have tried to compare UITextfield with NSString So your Code will never execute according to Your condition.

Try Using Below code

  @IBAction func LogIn(sender: AnyObject) {
            if(NameField.text == "" || PasswordField.text == "")
            {
                //Please Enter valid credential...
            }

            if(NameField.text != ""  && PasswordField.text != ""){
                //Login successfully...
            }
        }

Upvotes: 0

Related Questions