limiting characters after dot - java

780 Views Asked by At

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 [email protected]

3

There are 3 best solutions below

0
danielR On BEST ANSWER

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.

0
Sami Jaber On

To answer the specific question, you can limit the size by checking the size of the substring after the dot (assuming you only have on dot in the string):

afterDot = username.substring(username.indexOf("."))

But as stated by ZouZou, you should properly validate your email address (there's several other things to check for). Take a look at the example here: http://examples.javacodegeeks.com/core-java/util/regex/matcher/validate-email-address-with-java-regular-expression-example/

0
Lajos Arpad On

This should be helpful:

if (username.contains("@") && username.contains(".") && ((username.length() - username.lastIndexOf(".") <= 3)) {

Essentially it checks whether the difference of the String length and the last occurrence of dot is smaller or equal than 3. This handles emails like [email protected] as well.