markusenglund / react-switch

A draggable toggle-switch component for React. Check out the demo at:
https://react-switch.netlify.com/
MIT License
1.33k stars 101 forks source link

Better color hex validation #67

Open dreamyguy opened 4 years ago

dreamyguy commented 4 years ago

I think there could be a better color validation, since 4-digit hex values are perfectly fine and offer unique colors. Ie. all the hexes below are valid:

#aadd
#abcd
#affa
#baba
#dada
#cace

I've been working on a color validation package that could help:

https://www.npmjs.com/package/validate-color

This is how it could be applied to hexColorPropType.js:

import { validateHTMLColorHex } from 'validate-color';

// Make sure color props are strings that start with "#" since other ways to write colors are not supported.
const hexColorPropType = (props, propName, componentName) => {
  const prop = props[propName];
  if (
    !validateHTMLColorHex(prop)
  ) {
    return new Error(
      `Invalid prop '${propName}' supplied to '${componentName}'. '${propName}' has to be a hex-color string. Valid examples: '#abc', '#dada', '#123456'`
    );
  }
  return null;
};

export default hexColorPropType;