Skip to main content
2 of 2
deleted 2 characters in body; edited tags
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Simple code to check format of user inputted email address

I am helping a friend with her Java homework and I adapted a solution I used in a similar project of my own for this. It is supposed to use loose/generous regex to make sure an email entered matches the forms [email protected] or [email protected].

import java.util.Scanner;

public class App {
    
    Scanner scanner;
    
    public App() {
        this.scanner = new Scanner(System.in);
    }

    public static void main(String[] args) {
        App app = new App();
        
        app.GetUsername(true);
    }
    
    public void GetUsername(Boolean firstRun) {
        
        if(!firstRun) {
            System.out.println("The username you have entered was in an incorrect format. Must match [email protected]");
        } else {
            System.out.println("Please enter a username:");
        }
        
        String userInput = this.scanner.nextLine();
        
        UsernameCheck usernameCheck = new UsernameCheck(userInput);
        
        if(usernameCheck.isValid()) {
            System.out.println("Welcome, " + userInput + "!");
        } else {
            GetUsername(false);
        }
    }
    
}

UsernameCheck.java

import java.util.regex.*;

public class UsernameCheck {
    
    String username;
    
    public UsernameCheck(String username) {
        this.username = username;
    }
    
    public Boolean isValid() {
        return this.username.matches("[a-zA-Z0-9\\.]+@[a-zA-Z0-9\\-\\_\\.]+\\.[a-zA-Z0-9]{3}");
    }
}

I am most interested in hearing alternative solutions for re-prompting a user if the input they've given is invalid. This works in practice, but I am looking for the cleanest way to do it.

Stephen K
  • 215
  • 1
  • 2
  • 5