You can use TextFormatter and String's matches.
If the text in the TextField does not meet one of these three Regex, then show the old text.
case 1: newVal.matches("[A-z]") -> Single alpha character
case 2: newVal.matches("[A-z]\\d+") -> Alpha character followed by digits
case 3: newVal.matches("[A-z]\\d+[A-z]") -> Alpa character followed by digits than another alpha character.
Full app
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* @author blj0011
*/
public class JavaFXApplication149 extends Application
{
@Override
public void start(Stage primaryStage)
{
TextField textField = new TextField();
textField.setTextFormatter(new TextFormatter<>(c
-> {
if (c.getControlNewText().isEmpty()) {
return c;
}
if (c.getControlNewText().matches("[A-z]") || c.getControlNewText().matches("[A-z]\\d+") || c.getControlNewText().matches("[A-z]\\d+[A-z]")) {
return c;
}
else {
return null;
}
}));
StackPane root = new StackPane(textField);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
**Update: Change to TextFormatter. @kleopatra said it's the correct way to achieve this.