1

I already have this regular expression:

function check(){
    var re = /[0-9A-Fa-f]{6}/g;
    var inputString = document.getElementById("check").value;

    if(re.test(inputString)) {
         window.alert("Valid hex colour")
    } else {
         window.alert("Invalid hex colour")
    }

    re.lastIndex = 0;
}

And this is the input:

<input id="check" maxlength="6" placeholder="------">

This is the event listener:

document.getElementById('check').onkeydown=function(cc){
            if(cc.keyCode==13){
                check()
            }
            else if(cc.keyCode==46){
                document.getElementById("check").value = "";
            }
        }

This works fine. I also tried this regular expression:

/[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}/g;

But this also accepts hex values that are 3, 4, 5 or 6 characters long. How can you check for hex values that are exactly 3 or exactly 6 characters long using a regular expression? Thanks in advance.

Henry
  • 3,472
  • 2
  • 12
  • 36

1 Answers1

3

This works fine. I also tried this regular expression:

/[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}/g;

But this also accepts hex values that are 3, 4, 5 or 6 characters long.

You need anchors (and no global flag):

/^(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/

You can also add i to make it less verbose:

/^(?:[0-9A-F]{3}|[0-9A-F]{6})$/i

Without anchors, a four-digit hex string matches the {3} rule (since it contains a three-digit hex string).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875