How to check if color-hex-value is valid on keyup?

I try to make a script which check’s input’s value everytime when value changes. There must be ready example somewhere, but I just could not found it.

The value shoud be hex-color-value (like #FFFFFF), so script should check if the first character is # and after that only characters a-f, A-F and 0-9 are ok.

I quess it goes something like this:

function checkHex(value) {
// if value string includes only characters # a-f A-F 0-9 value is ok
// else value is not ok
}

<input type=“text” id=“hex_input” onkeyup=“checkHex(this)” />

A valid hex color has the form ‘#nnn’ or ‘#nnnnnn’.

function checkHex(value){
	return /^#([A-Fa-f0-9]{3}$)|([A-Fa-f0-9]{6}$)/.test(value)
}

checkHex(‘#ffffff’)

Thanks mrhoo! I know this, but I really need a code which check’s the characters every time when value changes in input. Not only when value is #fff or #ffffff.

There usage where I need this code is to change input´s className when user gives wrong characters in input-field. I also going to use this script to check other input values, like numeric values in non-numeric input´s etc.

I only need the if -sentence. Could somebody JS-Guru post it to me, please?

Very simple: if value contains characters A-F, a-f, 0-9

The checkHex function returns true if valid (matches regex) and false if invalid. So, to change class and such, create another function:

(untested)


function checkColor(colorForm)
{
     var color = colorForm.value;
     if (checkHex(color)) {
         colorForm.className = 'invalid-class-test';
     }
}

And set the onkeyup event handler to this function.