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:
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.