5

i am looking for code to validate html color codes. wanna check if user typed valid color code, can you guyz help ?

i know i need that regex stuff but i cant understand a think about that regex things :S

thanks

3 Answers 3

9

You can match hexadecimal colors like this:

if (/^#[0-9a-f]{3}([0-9a-f]{3})?$/i.test(str)) {
    //Match
}

Note that this wont handle names or rgb(n, n, n).

You can match rgb(x, y, z) colors like this:

if (/^rgb\s*(\s*[012]?[0-9]{1,2}\s*,\s*[012]?[0-9]{1,2}\s*,\s*[012]?[0-9]{1,2}\s*)$/i.test(str)) {
    //Match
}

Note that this will match rgb(299, 299, 299).

Sign up to request clarification or add additional context in comments.

6 Comments

It will handle #aaa which, while being a perfectly good CSS colour code is (like rgb()) not a valid HTML colour code.
?? 3-digit color codes are definitely valid. They mean the same as 6-digit codes, where the second digit of each color part is "0".
Note: you need to have a (?:) grouping around that second block (turning the string into if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(str)) - otherwise, color codes like #aba won't match.
@SLaks: when I put your regex test (/^#[0-9a-f]{3}[0-9a-f]{3}?$/i.test('#aba');) into Chrome's Javascript console, it returns false. EDIT: it also returns false in Firefox's JS console.
The parentheses need to be escaped for the RGB regex to work properly: /^rgb\s*\(\s*[012]?[0-9]{1,2}\s*,\s*[012]?[0-9]{1,2}\s*,\s*[012]?[0-9]{1,2}\s*\)$/i.test(str)
|
4

You could create an abstract element and attempt to apply the color to that element:

function validate_color(c) {
    var litmus = 'red';
    var d = document.createElement('div');
    d.style.color=litmus;
    d.style.color=c;
    //Element's style.color will be reverted to litmus or set to '' if an invalid color is given
    if( c !== litmus && (d.style.color === litmus || d.style.color === '')){
        return false;
    }
    return true;
}

1 Comment

This did exactly what I needed it to do, thanks! Quick question....I couldn't find much documentation for setting style.color. While it seems to work correctly in all the browsers I tested, is this behavior stated anywhere in any official documentation (that you can't set style.color to an invalid value)? Also, I noticed it doesn't mind if right parentheses are missing, for example "rgba(11,11,11" is valid. Not that it's a problem, just wondering why that would be the case?
0

It's 2020 so I created a npm package for this: https://www.npmjs.com/package/validate-color

It validates HTML colors by name, hex, rgb, rgba, hsl or hsla values.

  1. Validate ALL possible HTML colors:
   import validateColor from 'validate-color';

Usage:

   import React from 'react';
   import validateColor from 'validate-color';

   const ColorBox = props => {
     const {
       color = '',
       text = ''
     } = props;
     const theColor = color && validateColor(color) ? color : 'transparent';
     return (
       <div className="color-box" style={{backgroundColor: theColor}}>
         <p>{text}</p>
       </div>
     )
   };

   export default ColorBox;
  1. Validate only HTML colors (hex, rgb, rgba, hsl, hsla), without name:
   import { validateHTMLColor } from 'validate-color';
  1. Validate only color hex:
   import { validateHTMLColorHex } from 'validate-color';
  1. Validate only color name:
   import { validateHTMLColorName } from 'validate-color';

There's a demo page as well, featuring the validation applied to a React component:

https://dreamyguy.github.io/validate-color/

From there you'll find the link to the GitHub repo. Plenty of tests were written, for good measure. I do accept pull-requests, long live open-source!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.