How to validate if Textfield is empty?

Asked

Viewed 744 times

1

Good night, my friends

I am having difficulty in the following, I intend that the user receive a warning when the textfield is empty and if it pressed the button.

tried with the if condition (textFiel.text == "") but it didn’t work out, thanks for our help.

@IBAction func botton(_ sender: Any) {

    let celcius = Float(textFiel.text!)!
    let Fahrenheit:Float = (9 * celcius + 160) / 5
    label.text = "\(Fahrenheit)"


    if (textFiel.text == "") {
        label.text = "Por favor digite algo"
    }

}

4 answers

2


Another suggestion is to use the command Guard:

@IBAction func botton(_ sender: Any) {

    guard !((textField.text ?? "").isEmpty) else {
        label.text = "Por favor digite algo"
        return
    }
    let celcius = NSString(string: textField.text!).floatValue
    let Fahrenheit:Float = (9 * celcius + 160) / 5
    label.text = "\(Fahrenheit)"
}
  • Good morning, Edson of the error in the syntax (!textFiel.isEmpty), says that Value of type 'Uitextfiel' has no Member ' isEmpry ' It seems that the error is the declaration of variables or in the construction of the algorithm, all suggestions seem great just do not execute

  • Anselmo, I’ve fixed the code now.

  • This edition worked perfectly. thanks Edson and everyone for the help.

  • guard textField.text?.isEmpty == false else {

  • 1

    For iOS 10+ Uitextfield has a property called hasText exactly for this

1

I suggest you use the guard let, force ! is not a good practice.

guard let text = textField.text, !text.isEmpty else {
    return
}
  • iOS (10.0 and later) you can use the property hasText A Boolean value that indicates whether the text-entry Objects has any text.. guard textField.hasText else { return }

0

I think the idea is to check, besides if the text is empty, if it is not nil...

if textFiel.text != nil && !textFiel.text.isEmpty {
   label.text = "Por favor, digite algo"
}

0

Your code is comparing the objecto textFiel with the empty string (""). What you want, is to compare if the property text of the textFiel object contains or does not contain any text.

This can be done as follows:

if (let texto = textFiel.text, !texto.isEmpty)

Perhaps it would be better to carry out this validation before making the calculation:

@IBAction func botton(_ sender: Any) {

    if let texto = textFiel.text, !texto.isEmpty 
    {
        let celcius = Float(textFiel.text!)!
        let Fahrenheit:Float = (9 * celcius + 160) / 5
        label.text = "\(Fahrenheit)"
    else
    { 
        label.text = "Por favor digite algo"

    }
}

See the example

  • It did not work friend, the console is giving the following error: fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

  • Look at my issue.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.