In a TextField object in LibGDX I need to validate input characters to transform lowercase to uppercase, and avoid numbers and special chars. How can this be done? Thank you very much.
You can achieve this by adding a TextFieldFilter
to your TextField
and have that filter on valid characters.
textField.setTextFieldFilter(new TextField.TextFieldFilter() {
@Override
public boolean acceptChar(TextField textField, char c) {
return Character.isAlphabetic(c) && Character.isUpperCase(c);
}
});
This will make it so that the TextField
only accepts alphabetic uppercase input.
It might be slightly annoying to have to actually type in uppercase so another solution could be to only filter alphabetic, and override the change event to set the text to all uppcase when it has changed:
textField.setTextFieldFilter(new TextField.TextFieldFilter() {
@Override
public boolean acceptChar(TextField textField, char c) {
return Character.isAlphabetic(c);
}
});
textField.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
if (textField.getText() != textField.getText().toUpperCase()) {
int cursorPosition = textField.getCursorPosition();
textField.setText(textField.getText().toUpperCase());
textField.setCursorPosition(cursorPosition);
}
}
});