Làm thế nào để xác thực mã màu Hex trong java

Chuỗi xác thực mã màu hex

^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

 

Description

^                 # start of the line
 #                # must constains a "#" symbols
(                 # start of group #1
[A-Fa-f0-9]{6}  # bất kì kí tự a-z,A-Z,0-9, with length of 6
|                 #  or
[A-Fa-f0-9]{3}  # bất kì kí tự a-z,A-Z,0-9, with length of 3
)                 # end of group #1
$                 # 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 HexValidator {

 

    /**

     *  ^             #start of the line

     *  #           #  must constains a "#" symbols

     *  (             #  start of group #1

     * [A-Fa-f0-9]{6} #  any strings in the list, with length of 6

     * |            #    ..or

     * [A-Fa-f0-9]{3} #  any strings in the list, with length of 3

     *  )           #  end of group #1

     *  $           #end of the line

     */

    private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";

 

    public static void main(String[] args) {

        HexValidator hexValidator = new HexValidator();

        //check  hex color validate

        boolean isValid = hexValidator.validate("#aff");

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

    }

 

    /**

     * Validate hex color with regular expression

     *

     * @param hex hex color for validation

     * @return true valid hex color, false invalid hex color

     */

    public boolean validate(final String hex) {

        Pattern pattern = Pattern.compile(HEX_PATTERN);

        Matcher matcher = pattern.matcher(hex);

        return matcher.matches();

 

    }

}

Code UnitTest:

- “#1f1f1F”, “#AFAFAF”,”#1AFFa1″,”#222fff”, “#F00”, “#F00” : valid hex color

- “123456”: invalid– must start with a “#” symbol

- “#afafah” : invalid – “h” is not allow, valid letter from “a” to “f”

- “#123abce” : invalid – either 6 length or 3 length

- “aFaE3f”: invalid – must start with a “#” symbol, either 6 length or 3 length

- “F00”: invalid – must start with a “#” symbol

- “#afaf”: invalid – either 6 length or 3 length

- “#F0h” : invalid – “h” is not allow, valid letter from “a” to “f”

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

import org.testng.Assert;

import org.testng.annotations.*;

 

/**

 * Hex validator Testing

 * @author codewr

 *

 */

public class HexValidatorTest {

 

       private HexValidator hexValidator;

 

       @BeforeClass

        public void initData(){

              hexValidator = new HexValidator();

        }

 

       @DataProvider

       public Object[][] ValidHexProvider() {

              return new Object[][]{

                        {new String[] {

                           "#1f1f1F", "#AFAFAF","#1AFFa1","#222fff", "#F00"

                        }}

              };

       }

      

       @DataProvider

       public Object[][] InvalidHexProvider() {

              return new Object[][]{

                     {new String[] {

                              "123456","#afafah","#123abce","aFaE3f",

                              "F00","#afaf", "#F0h"  

                      }}

              };

       }

      

       @Test(dataProvider = "ValidHexProvider")

       public void ValidHexTest(String[] hex) {

             

          for(String temp : hex){

                 boolean valid = hexValidator.validate(temp);

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

                 Assert.assertEquals(true, valid);

          }

      

       }

      

       @Test(dataProvider = "InvalidHexProvider", dependsOnMethods="ValidHexTest")

       public void InValidHexTest(String[] hex) {

             

          for(String temp : hex){

                 boolean valid = hexValidator.validate(temp);

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

                 Assert.assertEquals(false, valid);

          }

      

       }

}

Output:

Running HexValidatorTest

Hex is valid : #1f1f1F , true

Hex is valid : #AFAFAF , true

Hex is valid : #1AFFa1 , true

Hex is valid : #222fff , true

Hex is valid : #F00 , true

Hex is valid : 123456 , false

Hex is valid : #afafah , false

Hex is valid : #123abce , false

Hex is valid : aFaE3f , false

Hex is valid : F00 , false

Hex is valid : #afaf , false

Hex is valid : #F0h , false

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.404 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>