Làm thế nào xác thực username trong java

Chuỗi xác nhận username phổ biển:

^[a-z0-9_-]{3,15}$

Description:

^                    # Bắt đầu tên
[a-z0-9_-]            # Tên được quay định chứa các kí tự sau: a-z,0-9,dấu gạch dưới, dấu gạch ngang
{3,15}  # Tên có độ dài là từ 3 đến 15
$                    # Kết thúc tên

Code:

package com.codewr.javacore.regular.expression;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

/**

 *

 * @author codewr

 */

public class UsernameValidator {

 

//   ^         # Start of the line

//  [a-z0-9_-] # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen

//   {3,15}    # Length at least 3 characters and maximum length of 15

//   $         # End of the line

    private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";

 

    public static void main(String[] args) {

        UsernameValidator usernameValidator = new UsernameValidator();

        //check  username validate

boolean isValid =usernameValidator.validate("codewr12");

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

    }

 

    /**

     * Validate username with regular expression

     *

     * @param username username for validation

     * @return true valid username, false invalid username

     */

    public boolean validate(final String username) {

        Pattern pattern = Pattern.compile(USERNAME_PATTERN);

        Matcher matcher = pattern.matcher(username);

        return matcher.matches();

 

    }

 

}

Code UnitTest:

- codewr12,  codewr_12, codewr-12 , codewr-12_smile : tên đúng

- co: tên sai vì chiều dài tên nhỏ hơn 3

- [email protected]: tên sai vì chứa kí tự không có trong chuỗi quy định @

 

- codewr123456789_- : tên sai vì chiều dài tên lớn hơn 15

 

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

import org.testng.Assert;

import org.testng.annotations.*;

 

/**

 * Username validator Testing

 * @author codewr

 *

 */

public class UsernameValidatorTest {

 

       private UsernameValidator usernameValidator;

 

       @BeforeClass

        public void initData(){

              usernameValidator = new UsernameValidator();

        }

 

       @DataProvider

       public Object[][] ValidUsernameProvider() {

              return new Object[][]{

                 {new String[] {

                    "codewr12", "codewr_12","codewr-12" ,"codewr-12_smile"

                 }}

               };

       }

      

       @DataProvider

       public Object[][] InvalidUsernameProvider() {

              return new Object[][]{

                 {new String[] {

                   "co","[email protected]","codewr123456789_-" 

                 }}

               };

       }

      

       @Test(dataProvider = "ValidUsernameProvider")

       public void ValidUsernameTest(String[] Username) {

             

          for(String temp : Username){

              boolean valid = usernameValidator.validate(temp);

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

              Assert.assertEquals(true, valid);

          }

      

       }

      

       @Test(dataProvider = "InvalidUsernameProvider",

                 dependsOnMethods="ValidUsernameTest")

       public void InValidUsernameTest(String[] Username) {

             

          for(String temp : Username){

              boolean valid = usernameValidator.validate(temp);

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

              Assert.assertEquals(false, valid);

          }

      

       }     

}

Output:

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

Running UsernameValidatorTest

Username is valid : codewr12 , true

Username is valid : codewr_12 , true

Username is valid : codewr-12 , true

Username is valid : codewr-12_smile , true

username is valid : co , false

username is valid : [email protected] , false

username is valid : codewr123456789_- , false

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

 

Results :

 

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

Chú ý: Thêm thư viện test vào file pom.xml

<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>6.8</version>

<scope>test</scope>

</dependency>