UITextField — Restrict textfield to a certain character (iOS)

Mr.Javed Multani
1 min readOct 3, 2020

If you want to perform a user input validation of your textfield use the following code snippet:

// MARK: - UITextFieldDelegatelet allowedCharacters = CharacterSet(charactersIn:”0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz”).invertedfunc textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {let components = string.components(separatedBy: allowedCharacters)
let filtered = components.joined(separator: "")if string == filtered {
return true} else {
return false }


#define ACCEPTABLE_CHARACTERS @”0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{NSCharacterSet *cs = [[NSCharacterSet
characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]
componentsJoinedByString:@""];return [string isEqualToString:filtered];

In addition you can also use character sets provided by apple to perform validation:

Take a look at https://developer.apple.com/reference/foundation/nscharacterset

let allowedCharacters = CharacterSet.alphanumerics.inverted
let allowedCharacters = CharacterSet.capitalizedLetters.inverted
Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer