Alyona
Alyona

Reputation: 1792

Regex for confirming acceptable input

I have KeyEvent.KEY_TYPED on which I perform my input check, during which I get full text by:

text = text + event.getCharacter();

But I need to make sure that I add only acceptable characters that user can input, that includes all digits, letters and special characters. Already app should support English, Estonian and Russian languages and more would be added in the future. What kind of regex should be to exclude Esc, Backspace etc?

Upvotes: 1

Views: 61

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

To match any char other than a control char, you may use

"\\P{Cc}"

or

"\\P{Cntrl}"

Upvotes: 1

eis
eis

Reputation: 53502

KEY_TYPED is only about keys that visually appear as input (hence key typed). To act on (and to disallow) control keys from being pressed such as backspace, you should be looking at other events, such as keyPressed and keyReleased. They get notifications also on control characters.

From KeyEvent javadoc:

"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered, and are the preferred way to find out about character input. In the simplest case, a key typed event is produced by a single key press (e.g., 'a'). Often, however, characters are produced by series of key presses (e.g., 'shift' + 'a'), and the mapping from key pressed events to key typed events may be many-to-one or many-to-many. Key releases are not usually necessary to generate a key typed event, but there are some cases where the key typed event is not generated until a key is released (e.g., entering ASCII sequences via the Alt-Numpad method in Windows). No key typed events are generated for keys that don't generate Unicode characters (e.g., action keys, modifier keys, etc.).

However, disallowing for example backspace does sound problematic from user perspective. If you want to go that route be careful that you've thought of all the relevant use scenarios. Since the keytyped event does not get any control characters, maybe it's already doing what you want it to do.

Upvotes: 1

Related Questions