3

I have two UITextInput controls that I want to count the number of characters in.

For context, I have two inputs: one for email address and one for password. I also have a “Login” button. The button is inactive by default, but as soon as at least one character is entered into both inputs, I’ll programatically enable the button. This is to prevent login attempts until the user has entered a value in both fields.

So far, I’m using this approach:

if count(emailInput.text) > 0 && count(passwordInput.text) > 0 {
    // Enable button
} else {
    // Disable button
}

Is using the count() function acceptable? Or is there a better way? As I recall there are some gotchas with checking the length of strings in iOS/Swift.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • Take a look at https://github.com/shamasshahid/SSValidationTextField. I wrote it because I was tired of writing separate views for validation. – Shamas S Jun 05 '15 at 14:02

3 Answers3

13

For me personally the following code has worked fine in past.

if (!emailInput.text.isEmpty && !passwordInput.text.isEmpty) { 
// enable button
} else {
// disable button
}
Shamas S
  • 7,507
  • 10
  • 46
  • 58
  • 1
    An `isEmpty` helper method? Awesome! Thank you! That’s much better. – Martin Bean Jun 05 '15 at 14:00
  • @MartinBean: `isEmpty` is a built-in property of the Swift `String` class, not a "helper method". – Martin R Jun 05 '15 at 14:06
  • @MartinR I meant it was a helpful method on the `UITextInput` class, rather than a global helper method (like `count`). Sorry for the misuse of terminology. – Martin Bean Jun 05 '15 at 14:25
5
if((emailInput.text!.characters.count) > 0 && (passwordInput.text!.characters.count) > 0) {
    // Enable button
} else {
    // Disable button
}
tatoline
  • 423
  • 6
  • 11
3

Swift 4

emailInput.text!.count

Swift 2

self.emailInput.text!.characters.count

but if you need to do something more elegant you can create an extension like this

Nowadays, after putting count directly on text property my guess is to use this directly without extension, but if you like to isolate this sort of things, go ahead!.

extension UITextField {

    var count:Int {
        get{
            return emailInput.text?.count ?? 0
        }

    }
}
ViTUu
  • 1,204
  • 11
  • 21