Làm thế nào để xác thực địa chỉ email trong java

Chuỗi xác thực địa chỉ email

^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*
      @[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

Description

^                         #start of the line
[_A-Za-z0-9-\\+]+ #  must start with string in the bracket [], must contains one or more (+)
(                         #   start of group #1
    \\.[_A-Za-z0-9-]+     #     follow by a dot "." and string in the bracket [], must contains one or more (+)
)*                        #   end of group #1,this group is optional (*)
    @                     #     must contains a "@" symbol
[A-Za-z0-9-]+      #       follow by string in the bracket [], must contains one or more (+)
(                         #         start of group #2- first level TLD checking
       \\.[A-Za-z0-9]+  #           follow by a dot "." and string in the bracket [], must contains one or more (+)
)*               #         end of group #2,this group is optional (*)
(                         #         start of group #3- second level TLD checking
       \\.[A-Za-z]{2,}  #           follow by a dot "." and string in the bracket [], with minimum length of 2
)                         #         end of group #3
$                         #end of the line

Code:

package com.codewr.javacore.regular.expression;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

/**

 *

 * @author codewr

 */

public class EmailValidator {

 

    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,})$";

 

    public static void main(String[] args) {

         EmailValidator emailValidator = new EmailValidator();

        //check  email validate

        boolean isValid = emailValidator.validate("[email protected]");

        System.out.println("email valid is " + isValid);

    }

 

    /**

     * Validate email with regular expression

     *

     * @param email email for validation

     * @return true valid email, false invalid email

     */

    public boolean validate(final String email) {

        Pattern pattern = Pattern.compile(EMAIL_PATTERN);

        Matcher matcher = pattern.matcher(email);

        return matcher.matches();

 

    }

}

Code Unit Test:

Email hợp lệ:

1. [email protected], [email protected], [email protected]
2. [email protected], [email protected], [email protected]
3. [email protected], [email protected]
4. [email protected], [email protected]

Email không hợp lệ:

1. codewr – must contains “@” symbol
2. [email protected] – tld can not start with dot “.”
3. [email protected] – “.a” is not a valid tld, last tld must contains at least two characters
4. [email protected] – tld can not start with dot “.”
5. [email protected] – tld can not start with dot “.”
6. [email protected] – email’s first character can not start with dot “.”
7. codewr()*@gmail.com – email’s is only allow character, digit, underscore and dash
8. [email protected]%*.com – email’s tld is only allow character and digit
9. [email protected] – double dots “.” are not allow
10. [email protected] – email’s last character can not end with dot “.”
11. [email protected]@gmail.com – double “@” is not allow
12. [email protected] -email’s tld which has two characters can not contains digit

import com.codewr.javacore.regular.expression.EmailValidator;

import org.testng.Assert;

import org.testng.annotations.*;

 

/**

 * Email validator Testing

 *

 * @author codewr

 *

 */

public class EmailValidatorTest {

 

       private EmailValidator emailValidator;

 

       @BeforeClass

       public void initData() {

              emailValidator = new EmailValidator();

       }

 

       @DataProvider

       public Object[][] ValidEmailProvider() {

              return new Object[][] { { new String[] { "[email protected]",

                     "[email protected]", "[email protected]",

                     "[email protected]", "[email protected]",

                     "[email protected]", "[email protected]",

                     "[email protected]", "[email protected]",

                     "[email protected]" } } };

       }

 

       @DataProvider

       public Object[][] InvalidEmailProvider() {

              return new Object[][] { { new String[] { "codewr", "[email protected]",

                     "[email protected]", "[email protected]", "[email protected]",

                     "[email protected]", "codewr()*@gmail.com", "[email protected]%*.com",

                     "[email protected]", "[email protected]",

                     "[email protected]@gmail.com", "[email protected]" } } };

       }

 

       @Test(dataProvider = "ValidEmailProvider")

       public void ValidEmailTest(String[] Email) {

 

              for (String temp : Email) {

                     boolean valid = emailValidator.validate(temp);

                     System.out.println("Email is valid : " + temp + " , " + valid);

                     Assert.assertEquals(valid, true);

              }

 

       }

 

       @Test(dataProvider = "InvalidEmailProvider", dependsOnMethods = "ValidEmailTest")

       public void InValidEmailTest(String[] Email) {

 

              for (String temp : Email) {

                     boolean valid = emailValidator.validate(temp);

                     System.out.println("Email is valid : " + temp + " , " + valid);

                     Assert.assertEquals(valid, false);

              }

       }

}

Output:

Running EmailValidatorTest

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : codew[email protected] , true

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : [email protected] , true

Email is valid : codewr , false

Email is valid : [email protected] , false

Email is valid : [email protected] , false

Email is valid : [email protected] , false

Email is valid : [email protected] , false

Email is valid : [email protected] , false

Email is valid : codewr()*@gmail.com , false

Email is valid : [email protected]%*.com , false

Email is valid : [email protected] , false

Email is valid : [email protected] , false

Email is valid : [email protected]@gmail.com , false

Email is valid : [email protected] , false

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.446 sec

 

Results :

 

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

Chú ý: file pom.xml add maven

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>6.8</version>

<scope>test</scope>

</dependency>