Search code examples
iosswiftuitextfielduikeyboard

How to prevent "0" as the first character and limit number of characters allowed in UITextField using Swift?


I want to achieve following:

  1. Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
  2. Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
  3. Limit the character count to 10.
  4. Only allow numbers. No Copy-Paste text values.

I am using decimal keypad. Below code handles first and third item above:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return newString.count <= 10
}

Thank you for your time.


Solution

  • Bellow code will check all conditions you have specified

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        
        //Prevent "0" characters as the first characters. (i.e.: There should not be values like "003" "01" "000012" etc.)
        if textField.text?.count == 0 && string == "0" {
            
            return false
        }
        
        //Limit the character count to 10.
        if ((textField.text!) + string).count > 10 {
            
            return false
        }
        
        //Have a decimal keypad. Which means user will be able to enter Double values. (Needless to say "." will be limited one)
        if (textField.text?.contains("."))! && string == "." {
            
            return false
        }
    
        //Only allow numbers. No Copy-Paste text values.
        let allowedCharacterSet = CharacterSet.init(charactersIn: "0123456789.")
        let textCharacterSet = CharacterSet.init(charactersIn: textField.text! + string)
        if !allowedCharacterSet.isSuperset(of: textCharacterSet) {
            return false
        }
        return true
    }