Page 1 of 1

Validating An HTML Hex Color (not regex... i dont think)

Posted: Tue Apr 25, 2006 1:44 am
by s.dot
I have a text input field that a user may enter an HTML color in. Like #FF0000, #0000FF, et cetera. How can I validate that this is a good HTML color and not just a six/7 word like 'yousuck'?

I've thought about it, and the websafe colors only use CC FF 00 33 66 99. So I could build an array of 216 colors based on that and check against it.

But I also want them to be able to put in other colors, like #9E8F3D for example. Then I remembered that all colors have an RGB value like 255,0,255 but I don't know how to convert and build an array or something to check against.

I've looked at the functions bin2hex hex2dec or the likes (cant remember exact names) but can't tell which one I need to use, or how to build something to check against.

psuedo code:

Code: Select all

if(isValidColor($_POST['color'])){
    $color = $_POST['color'];
} else {
    $color = '#000000';
}

Posted: Tue Apr 25, 2006 3:30 am
by jito
you can try this, $color is a string and it has always 7 charecters in it.using substr() you can get each charecter individually. here the first charecter is always a '#' and the next 6 are between 1 to 9 or A to F. is that what u wanted?
use array() function to create a array of elements 1 to 9 and A to F.

Posted: Tue Apr 25, 2006 3:41 am
by asgerhallas
Why not regex?

Code: Select all

if (preg_match("/^\#[0-9A-Fa-f]{6}$/", $color)) 
{
      // the color is valid
}

Posted: Tue Apr 25, 2006 4:02 am
by feyd
dechex() and hexdec() would the be ones to use here, as far as what scottayy is talking about, but I don't see a not to use regex for simple checking.

Posted: Tue Apr 25, 2006 4:37 am
by Ollie Saunders
php manual on hexdec wrote:hexdec() will ignore any non-hexadecimal characters it encounters.
as long as that behaviour is acceptable use hexdec

Posted: Tue Apr 25, 2006 4:46 am
by Ollie Saunders
ole wrote:
php manual on hexdec wrote:hexdec() will ignore any non-hexadecimal characters it encounters.
as long as that behaviour is acceptable use hexdec
no wait you i'll have to split the string into 2 character chunks before hexdecing it. chunk_split