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
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).
if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(str)) - otherwise, color codes like #aba won't match./^#[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./^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)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;
}
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.
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;
hex, rgb, rgba, hsl, hsla), without name: import { validateHTMLColor } from 'validate-color';
hex: import { validateHTMLColorHex } from 'validate-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!