0

I am limiting the input in a UITextField to only characters from the alphabet like this in shouldChangeCharactersIn:

switch textField {
    case descriptionTextField:
        return prospectiveText.containsOnlyCharactersIn(matchCharacters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZáäâàæãåāéëêèęėēóôòõœøōúüûùūíïìîįīÁÄÂÀÆÃÅĀÓÖÔÒÕŒØŌÚÜÛÙŪÍÏÌÎĮĪ ") && prospectiveText.count <= 51
    default:
        return true
}

Now while this works like a charm, I want to allow users to insert emoji as well. Is there any way I can accomplish this? I don't want them to insert numbers or special characters though.

PennyWise
  • 595
  • 2
  • 12
  • 37
  • 1
    You should never hardcode allowed characters. Use `CharacterSet.letters` to check if a String contains only letters. As for emojis, have a look at [Find out if character in string is emoji](https://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji) – Dávid Pásztor Feb 28 '19 at 11:39
  • Could you elaborate on why I should not hardcode allowed characters? I believe you though - but would like to know why. Thanks for the input! – PennyWise Feb 28 '19 at 11:43
  • 1
    Because you can never iterate all characters for sure, especially for all different locales. `CharacterSet` exists for a reason, it has sets for pretty much all `Unicode` categories, so you can be sure that it handles all possible inputs correctly. There's way more possible characters than what you could safely and certainly hardcode, so most probably you'll leave some valid inputs out. – Dávid Pásztor Feb 28 '19 at 12:10

1 Answers1

0

Simply check reverse condition, in condition, include the number and all special characters, and put '!' before prospectiveText.containsOnlyCharactersIn so if found any number and special character which is you have specified then it will return false.

switch textField {
    case descriptionTextField:
        return !prospectiveText.containsOnlyCharactersIn(matchCharacters: "<put here numbers and all your symbols you want to ignore> ") && prospectiveText.count <= 51
    default:
        return true
}
AtulParmar
  • 4,358
  • 1
  • 24
  • 45