开发者

validating html color codes JS

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

开发者_如何学JAVA

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


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.

  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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜