0

GOAL:

I'm trying to validate the user's email address as he/she types.

I'm just using simple regex because I don't want to use any external library. Also if use the regex like in here regex email for java I'm encountering error PatternSyntaxException that's why I prefer simple regex for now.

So I put the TextFormatter and UnaryOperator inside the initialize method.

    @FXML
public void initialize()
{

    //1. USE UNARY FIRST TO MAKE FILTER BEFORE USING TEXTFORMATTER
    UnaryOperator <TextFormatter.Change> filterEmail = (change ->{
          
        if(change.getControlNewText().matches("^(.+)@(.+)$*"))
        {
                lblEmailError.setVisible(false);
                txtEmailAdd.setBorder(null);
                return change;
                
        }
            
        
        else
        {
            lblEmailError.setText("Invalid Email");
            lblEmailError.setVisible(true);
            txtEmailAdd.setBorder(new Border(new BorderStroke(Color.RED, BorderStrokeStyle.SOLID, new CornerRadii(3), new BorderWidths(2), new Insets(-2))));
            return null;
        }
        
        
    });
    
    TextFormatter <String> tf = new TextFormatter<String>(filterEmail);
    txtEmailAdd.setTextFormatter(tf);
   
    
}

But as long as the FXML loads I can't type anymore in the TextField and can't be edited anymore. I can't type anything. Maybe there is something wrong with my condition or I'm wrong putting it inside the initialize method.

enter image description here

I'm lost. I have already dug the web on how to validate email in java using regex. like this Java regex email

I'm also using SceneBuilder to build the fxml. Any help will do thanks in advance.

lelouch
  • 35
  • 8
  • Try `".*(?:@.*)?"` if you need a pattern to validate live input. Then use `".+@.+"` to validate the final input value. – Wiktor Stribiżew Apr 08 '22 at 09:12
  • I tried to use `".*(?:@.*)?"` but it allows double @ or invalid emails. I don't know how to validate using `".+@.+"` for the final value. My goal here is to check the `TextField` for invalid format emails while the user is typing. – lelouch Apr 08 '22 at 10:59
  • Yes, and your regex would also allow that. – Wiktor Stribiżew Apr 08 '22 at 11:00
  • Yes, so can you point me in the right direction how to achieve what I want? – lelouch Apr 08 '22 at 11:01
  • [How can I validate an email address using a regular expression?](https://stackoverflow.com/q/201323/3832970) and https://emailregex.com/ – Wiktor Stribiżew Apr 08 '22 at 11:02
  • If you need to avoid multiple `@`, you can try this: `[^@]+(?:@[^@]*)?` for live matching and `[^@]+@[^@]+` for final validation. What are the other cases in which it doesn't work? @lelouch – lemon Apr 13 '22 at 00:34

0 Answers0