Max character limit of UITextField and allowed characters Swift

Setting the maximum characters limit or the allowed characters in UITextField is very common in the project. In this article, we are going to make it very easy so we can achieve this feature in just one line of code. Let’s get started.

Added new feature:

Added support of custom allowed characters using just one line of code
// Accept only given character in string, this is case sensitive
@IBInspectable var allowedCharInString: String = ""

Adding Subclass of UITextField

– Create a New project
– Add new file and choose Cocoa Touch Class

– Create a subclass of UITextField and choose name SDCTextField or any other name

Now add Below code in SDCTextField class
import UIKit

enum ValueType: Int {
    case none
    case onlyLetters
    case onlyNumbers
    case phoneNumber   // Allowed "+0123456789"
    case alphaNumeric
    case fullName       // Allowed letters and space
}

class SDCTextField: UITextField {
    
    @IBInspectable var maxLength: Int = 0 // Max character length
    var valueType: ValueType = ValueType.none // Allowed characters

    /************* Added new feature ***********************/
    // Accept only given character in string, this is case sensitive
    @IBInspectable var allowedCharInString: String = ""

    func verifyFields(shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        switch valueType {
        case .none:
            break // Do nothing
            
        case .onlyLetters:
            let characterSet = CharacterSet.letters
            if string.rangeOfCharacter(from: characterSet.inverted) != nil {
                return false
            }
            
        case .onlyNumbers:
            let numberSet = CharacterSet.decimalDigits
            if string.rangeOfCharacter(from: numberSet.inverted) != nil {
                return false
            }
            
        case .phoneNumber:
            let phoneNumberSet = CharacterSet(charactersIn: "+0123456789")
            if string.rangeOfCharacter(from: phoneNumberSet.inverted) != nil {
                return false
            }
            
        case .alphaNumeric:
            let alphaNumericSet = CharacterSet.alphanumerics
            if string.rangeOfCharacter(from: alphaNumericSet.inverted) != nil {
                return false
            }
            
        case .fullName:
            var characterSet = CharacterSet.letters
            print(characterSet)
            characterSet = characterSet.union(CharacterSet(charactersIn: " "))
            if string.rangeOfCharacter(from: characterSet.inverted) != nil {
                return false
            }
        }
        
        if let text = self.text, let textRange = Range(range, in: text) {
            let finalText = text.replacingCharacters(in: textRange, with: string)
            if maxLength > 0, maxLength < finalText.utf8.count {
                return false
            }
        }

        // Check supported custom characters
        if !self.allowedCharInString.isEmpty {
            let customSet = CharacterSet(charactersIn: self.allowedCharInString)
            if string.rangeOfCharacter(from: customSet.inverted) != nil {
                return false
            }
        }
        
        return true
    }
}

Adding SDCTextField in ViewController

Now open your Viewcontroller Nib file and drag and drop a UITextField

1. Select Identity Inspector
2. Change the class from UITextField to SDCTextField
3. Create an IBOutlet of this UITextField
Now open your ViewController class and add UITextFieldDelegate functions like below
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: SDCTextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.textField.delegate = self
    }
}

extension ViewController: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // Verify all the conditions
        if let sdcTextField = textField as? SDCTextField {
            return sdcTextField.verifyFields(shouldChangeCharactersIn: range, replacementString: string)
        }
    }
}

Now we are all set to use features like max character length and allowed characters

Setting the max characters limit

Now we are going set max characters limit to 10. In our viewDidLoad function just write one line of code as below.
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.textField.delegate = self
    self.textField.maxLength = 10
}
Now run the code

Allow only custom characters

If you want that your UITextField should accept only characters which you wants, then just write one line of code in your viewDidLoad function which is below
self.textField.allowedCharInString = "1234abcde"
Note: This is case sensitive, if you want to allow both "a" and "A" then just add both of them in allowedCharInString

Allow only letters in UITextField

By writing just one line of code we can easily set only letters in UITextField. Write below code in your viewDidLoad functions
self.textField.valueType = .onlyLetters

Allow only numbers

Just add below one line of code in viewDidLoad functions and we are done
self.textField.valueType = .onlyNumbers

We can also set other allowed character set, just have a look of below enum
enum ValueType: Int {
    case none
    case onlyLetters
    case onlyNumbers
    case phoneNumber   // Allowed "+0123456789"
    case alphaNumeric
    case fullName       // Allowed letters and space
}

You can add your cases inside the enum to achieve required features
Read our next article: Everything about CAGradientLayer in just 5 mins

5 comments on “Max character limit of UITextField and allowed characters Swift

  1. Michel Ortega

    Thank you very much for this tutorial.
    I guess there’s a return missing in the textField shouldChangeCharactersIn method inside the delegate.
    XO.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *