SIMPLE JAVAFX TEXTFIELD INPUT VALIDATION

SIMPLE JAVAFX TEXTFIELD INPUT
                   VALIDATION
"ON KEY RELEASED"

In this example we will validate the user name with the following regex expression.

String regex=”[A-Za-z\\s]+”  this means only accept capital letters or small “[A-Za-z]”and white space characters  “//s” ,The + is a quantifier  ,it means match one or more occurrences  “[A-Za-z]”.

public class Validation extends Application {

 @Override
public void start(Stage primaryStage)   {      
 
          Font font=Font.font("castellar", 16);

          Label user_name_label=new Label("User Name :"); 
          Label error_label=new Label(“Valid”);   
          error_label.setFont(font);

            StackPane stackPane=new StackPane();

            GridPane root=new GridPane();  
            root.setHgap(10);  
            root.setPadding(new Insets(5,5,5,5));  
            root.setMaxWidth(600);
            root.setMaxHeight(200);  

            StackPane.setAlignment(root, Pos.CENTER);  
             user_name_label.setFont(font);  

          TextField user_name=new TextField();  
         user_name.setMinWidth(200);
         user_name.setOnKeyReleased(new EventHandler<KeyEvent>(){

     @Override
  public void handle(KeyEvent event) {

   if( isValidName(user_name.getText() ) ){      
        
              error_label.setStyle("-fx-text-fill:green");
              error_label.setText("Valid");
  }else{              
           error_label.setText("Invalid User Name");
           error_label.setStyle("-fx-text-fill:red");
           error_label.setFont(font);
 }
  }      
 });

   root.add(user_name_label, 0, 0);
   root.add(user_name, 1, 0);
   root.add(error_label, 2, 0);
   root.setStyle("-fx-background-color:aqua;-fx-border-width:3;-fx-border-color:black;");  

  stackPane.getChildren().add(root);  
  stackPane.setStyle("-fx-background-color:black;") ;
  
  Scene scene = new Scene(stackPane,700, 350);
  primaryStage.setTitle("KeyReleased Validation");
  primaryStage.setScene(scene);
  primaryStage.show();
}
 public boolean isValidName(String s){      
     String regex="[A-Za-z\\s]+";      
      return s.matches(regex);//returns true if input and regex matches otherwise false;
 }
}
Results:
Any character other than letters and whitespace produces the following.

The correct match

Comments

Popular Posts