1

I'm trying to validate a textfield for hex colors only using regex. I stumbled upon this answer, and tried it for my textField, and it doesn't work as I expect it to. Here's the code:

/^[0-9A-F]{6}$/i.test(e.target.value)

It's supposed to check if the textfield is 0 - 9 || A - F (capital or lowercase), but when I log that, it always says false.

How can I validate a hex textfield?

Full Code:

JSFiddle

document.getElementById('hexTextField').addEventListener('keyup', function(e) {
  // Allow: tab, home, end, left, up, right, down
  if ([9, 36, 35, 37, 38, 39, 40].indexOf(e.keyCode) !== -1 ||
    // Allow: Ctrl || Command && a, c, x and v
    (!0 === e.ctrlKey || !0 === e.metaKey) && /65|67|88|86/.test(e.keyCode)) {
    if (e.keyCode === 86 && /(^[0-9A-F]{6}$)|(^[0-9A-F]{3}$)/i.test(e.target.value)) {
      //myColor.setColor(e.target.value, 'hex');
    }
    return;
  }

  console.log(/^[0-9A-F]{6}$/i.test(e.target.value));
  if (/^[0-9A-F]{6}$/i.test(e.target.value)) {
    //myColor.setColor(e.target.value, 'hex');
  } else {
    e.preventDefault();
  }
});
<input type="text" id="hexTextField" spellcheck="false" maxlength="6">

Update

There seems to be some confusion of what exactly I'm asking. I'm trying to validate the textField as the user is typing, not when the user finished. I hope this will clarify my question.

Community
  • 1
  • 1
Jessica
  • 9,379
  • 14
  • 65
  • 136

1 Answers1

0

What the regex code does is, it checks if the textfield has the 'valid' chars, && if there are 6 chars in the textfield.

So if one would want to validate the textfield as the user types, you would use this regex:

/[0-9A-Fa-f]$/i

Notice, I removed the {6} which comes out to true only if there are 6 chars.

Jessica
  • 9,379
  • 14
  • 65
  • 136