0

I need to validate alphabetical characters in a text field. What I have now works fine, but there is a catch, I need to allow accented characters (like āēīūčļ) and on a Latvian keyboard these are obtained by typing the singlequote first ('c -> č), so my validator fails is the user types the singlequote and a disallowed character like a number, obtaining '1.

I have this coffeescript-flavor jQuery webpage text entry field validator that only allows alphabetical characters (for entering a name).

allowAlphabeticalEntriesOnly = (target) ->
  target.keypress (e) ->
    regex = new RegExp("[a-zA-Z]")
    str = String.fromCharCode((if not e.charCode then e.which else e.charCode))
    return true  if regex.test(str)
    e.preventDefault()
    false

And it gets called with:

allowAlphabeticalEntriesOnly $("#user_name_text")

The code and regex work fine, denying input of most everything except small and large letters and the singlequote, where things get tricky.

Is there a way to allow accented characters with the singlequote layout, but deny entry of forbidden characters after the quote?

EDIT: If all else fails, one can implement back-end invalid character deletion a-la .gsub(/[^a-zA-Z\u00C0-\u017F]/, ''), which is what I ended up doing

Epigene
  • 3,634
  • 1
  • 26
  • 31

1 Answers1

0

Try using [a-zA-Z\u00C0-\u017F] to match a-z and accented characters (all characters within unicode range specified).

See: Matching accented characters with Javascript regexes

Community
  • 1
  • 1
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • This would work great for keyboard layouts using Alt(Option) key to trigger accented characters, however my users primarily use the singlequote key and it seems to completely escape the regex, allowing entries in the name field like "'@'9'+". Furthermore, [^\'] does not prevent its entry (nor should it, I need people to be able to get accents with it). Any way to enforce typing of allowed characters **after** a typed singlequote? – Epigene Apr 14 '14 at 06:19
  • Sounds like your issue might not be to do with regex, but more that you are validating on key-up, and modifying the user input to strip invalid characters before the user blurs the field. I would expect [^\'] to prevent it's entry, but having no insight into the keyboard setup you are using, it is hard to guess the problem. Perhaps you could try validating the field on blur event instead? – Billy Moon Apr 14 '14 at 18:24