Email verification in Java

Asked

Viewed 9,295 times

3

I am doing a simple test to check if the user has typed a valid email. So I have an error of syntax in token "@" invalid Assignmentperator.

Code of the main class:

public class Email {

static String email = "[email protected]";

public static void main(String[] args) {

}

public static void validarEmail(){

    //Verifica a posicao do @ no emal.
    int validarEmail = email.indexOf("@");
    //System.out.println(validarEmail);

}

public static void obterNome(){

    //Seleciona o que esta escrito antes do @.
    String obterNome = email.substring(0, 6);
    //System.out.println(obterNome);

}   

Class that checks the Email:

public class VerificaEmail {

public static void main(String[] args) {

    Email e = new Email();

    //Verifica se o Email e valido.
boolean b = e.validarEmail([email protected]);
    if(!b)
        System.out.println("Email Inválido");
    else
        System.out.println("Email Válido");

// Imprime o que esta antes do @.
String nome = e.obterNome([email protected]);
System.out.println(nome);

}
  • If I put in String and the email in quotes does not work tbm.

  • But the error when email (in the two calls inside VerificaEmail) is in quotes is different, right?

  • if I place the class emails verificaEmail quotation marks it shows the following error - test cannot be resolved to a variable - Syntax error on token "@", invalid Assignmentperator - pessoa cannot be resolved to a variable - The method validarEmail() in the type Email is not applicable for the Arguments (String) And them and the same email from the main class.

  • 2

    "person cannot be resolved to a variable" this error is precisely pq you are passing without the quotation marks, should be boolean b = e.validarEmail("[email protected]");

  • @Math I’ve tried to do it this way with the most error quotes tbm

  • But at least it must be another mistake, it’s not?

  • @re22 In fact, the way he put it worked but I ended up discovering what was causing the error. And I used other methods to solve the problem. But remembering that the way he put tbm works only that it is more complex and mine became easier.

Show 2 more comments

3 answers

9


The best way to validate an email is to apply a regular expression.

Pattern as static member

in your Email class create a static and final private member of the Pattern type

private static final String EMAIL_PATTERN = 
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

private static final Pattern pattern = Pattern.compile(EMAIL_PATTERN, Pattern.CASE_INSENSITIVE);

Use a Matcher within your email validation method

public static boolean validarEmail(String email){
    Matcher matcher matcher = pattern.matcher(email);
    return matcher.matches();
 }

Note that it is better to leave the Pattern as static and already compiled so, you do not need to create a new one with each new validation, you win in performance

It needs to be RFC822 compliance?

Example RFC822

****Note that I changed the return of your method to boolen, so it makes more sense for client classes to call their method

  • 1

    Just one note: e-mail validation with regex is not 100% safe as it is not totally compliant with the specification (RFC). False positives and false negatives may occur, so the tip is always test carefully so that the solution is good enough to meet your needs. For more details, see this other issue.

  • 1

    Cool, thanks for the tip @utluiz I put a reference to precede this RFC case. If necessary, ask me to make a full translation of the reply in English. Thank you again.

2

Does Your Email Class Need a Main Method? If you want to record an informed email to it a builder would make more sense.

public class Email {

static String email;

public Email(String email){
    this.email = email;
}  

//public static void validarEmail(){
public boolean validarEmail()
    //Verifica a posicao do @ no emal.
    //int validarEmail = this.email.indexOf("@");
    //System.out.println(validarEmail);

    return ( this.email.indexOf('@') > 0 );    
}

public static String obterNome(){

    //Seleciona o que esta escrito antes do @.
    return this.email.substring(0, this.email.indexOf('@'));
    //System.out.println(obterNome);

}

There in the other class:

public class VerificaEmail {

public static void main(String[] args) {

    Email e = new Email("[email protected]");

    //Verifica se o Email e valido.
    if(!e.validarEmail())
        System.out.println("Email Inválido");
    else
        System.out.println("Email Válido");


    System.out.println(e.obterNome());

}
  • I used your code so I still have some errors that I am not able to solve. On the lines return obterNome = this.email.substring(0, this.email.indexOf('@')); Email e = new Email("[email protected]"); if(!e.validarEmail()) String nome = e.ObterNome("[email protected]");.

  • It was incorrect, I edited the code right here in the post, so I didn’t notice. But see that the solution proposed by @Filipe Gonzaga Miranda is much more interesting. What I did here was just an adjustment to your code.

0

I ended up finding a simpler way to solve my errors follows the code:

*Email class:

public class Email {

public static String email = "[email protected]";
public static String Nome;
public static int indiceEmail;

public static boolean validarEmail(){

    //Verifica se o email possui o @.
    indiceEmail = email.indexOf('@');
    if (indiceEmail > 0)
        return(true);
    else
        return(false);  

}

public static String obterNome(){

    if (indiceEmail > 0)
        return Nome = email.substring(0, indiceEmail);
    else
        return("Erro!");        

}   

Main class:

public class VerificaEmail {

public static void main(String[] args) {

    Email e = new Email();      

//Verifica se o Email e valido.
boolean b = e.validarEmail();
    if(!b)
        System.out.println("Email Inválido");
    else
        System.out.println("Email Válido");

// Imprime o que esta antes do @.
String nome = e.obterNome();
System.out.println(nome);

}

This way it became simpler and better to understand and without altering the intention of the author.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.