-1

I'm able to limit the length using the code below, but I can't seem to find a way to also limit special characters.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = count(textField.text.utf16) + count(string.utf16) - range.length
if (textField.placeholder == "USERNAME")
{
    //Also limit special characters here
    return newLength <= 15 // Bool
}

characters I want allowed:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.

I tried following this link but its in objective C and I'm having trouble merging it with my current 15 character limit code above

Community
  • 1
  • 1
SlopTonio
  • 1,085
  • 1
  • 15
  • 39

2 Answers2

3

Alternative to regex, you can first get all the allowed characters into a set:

 var charactesAllowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."
 var charactersSet = [Character](charactesAllowed)

then try to see if the most recently typed charactes is in this array

var newCharacter = //whatever the character is, ex: "A"
if(contains(charactersSet, newCharacter))
{
    println("Allowed")
    // Add it into the label text
}
dorian
  • 801
  • 5
  • 11
  • I used this as a reference and it led me to what I was looking for. I had to create an extension for contains – SlopTonio Aug 06 '15 at 14:24
-3
let  ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"


if textField == textFieldNumber{
            let characterSet = CharacterSet.init(charactersIn: ACCEPTABLE_CHARACTERS).inverted
            maxLength = 11
            let currentString: NSString = textField.text! as NSString
            let newString: NSString =
                currentString.replacingCharacters(in: range, with: string) as NSString
            let filter = string.components(separatedBy: characterSet).joined(separator:"")
            return ((string == filter) && newString.length <= maxLength!)
        }
AS Mackay
  • 2,463
  • 9
  • 15
  • 23
krishnendra
  • 513
  • 5
  • 7