Search code examples
iosswiftuitextfieldswift5

Swift5: TextField Minimum and Maximum Character Limit Validation


I am trying to validate Minimum 6 characters and Maximum 20 characters in TextField. Below is the code validation .

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let curruntCharachterCount = textField.text?.count ?? 0
    if range.length + range.location > curruntCharachterCount{
        return false
    }
    let newLength = curruntCharachterCount + string.count - range.length
    return newLength <= 20
}

How should i set Minimum character length validation. Please suggest.


Solution

  • You can do like below

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
            if let text = textField.text,
               let textRange = Range(range, in: text) {
                let updatedText = text.replacingCharacters(in: textRange,with: string)
                if updatedText.count <= 6 {
                    print("minimum 6")
                }else if updatedText.count >= 20{
                    print("max 20")
                    return false
                }
            }
            return true
        }