2

I'm looking for a way to minimize characters in textfield. Since the textfield is for username input, I want to make users input 4 characters minimum to 30 characters maximum. First, I made textfield shouldChangeCharactersIn to set maximum characters in textfield. The code looks good but the problem when I want to make users if the username text field is less than 4 characters the app gives them error or to return false.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 

let currentString = usernameTextField.text!.characters.count ?? 0
        if (range.length + range.location > currentString) {
            return false
        }
        let newLength = currentString + string.characters.count - range.length
        return newLength <= 30
    }

Any help ?

Abdul Karim
  • 4,359
  • 1
  • 40
  • 55
user2508528
  • 131
  • 1
  • 3
  • 9

2 Answers2

1

I would implement the textFieldShouldEndEditing(_:) delegate method. If the current length is too short, return false and optionally present some sort of message/indicator so the user knows what is wrong.

I would also update textField(_:shouldChangeCharactersIn:replacementString:) to check if the new length is too short. If so, disable a Save button or some other appropriate UI component(s) letting the user know they have something to fix.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
1
func textFieldShouldReturn(textField: UITextField) -> Bool {
    let fieldTextLength = textField.text!.characters.count

    if  fieldTextLength < 4 || fieldTextLength  > 30 {
        //do something about it
    }
    self.view.endEditing(true)
    return true
}

Didn't really understand your problem at the end but this should do it!

Mike JS Choi
  • 1,081
  • 9
  • 19
  • The problem is when any users input usernameTextField less then 4 and greater then 30 characters it's give him a false. I did the last part (greater then 30 character) but I couldn't find a solution for less then 4 characters – user2508528 Dec 10 '16 at 03:03
  • This is not the proper approach. This code still allows the keyboard to be dismissed even if the text field is too short or too long. – rmaddy Dec 10 '16 at 03:35