Search code examples
javastring-lengthlimiting

limiting characters after dot - java


Hey so I'm doing a project for school. We have to code a virtual atm machine. You would have to log in with your student mail.

My question is : How do I limit character length after a dot(.)?

public boolean validUsername(String username) {
        Boolean oneAT = false;
        for (int i=0; i < username.length(); i++) {
            if (username.contains("@") && username.contains(".") &&{
                oneAT = true;
            }
        }

        return oneAT;
    }

The function checks if the username typed, contains a @ and a .(dot). Is there a way to limit character length to three after the dot ? Otherwise the user can write johndoe@johndoemail.tugfksdoew


Solution

  • It's easier to validate the username with a regular expression

    public boolean validUsername(String username) {
        Pattern pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
        Matcher matcher = pattern.matcher(username);
        return matcher.matches();
    }
    

    The expression validates if the username is a valid email address and returns true if so.