color.js icon indicating copy to clipboard operation
color.js copied to clipboard

Would be good to have an isValid helper

Open fatih-erikli opened this issue 1 year ago • 11 comments

Currently I call Color(string) and treat it as valid if an exception was not thrown. It would be good to have an isValid function exported in the module.

fatih-erikli avatar Jun 06 '23 21:06 fatih-erikli

I wonder if we could feed two birds with one scone by making Color.get() / getColor() not error (see #518 ). Then you can just check if the return value === null.

LeaVerou avatar May 28 '24 00:05 LeaVerou

Exceptions are not thrown for all invalid colors however. If using oklch("z" 100 230) the returned .toString value would be oklch(NaN 100 230). Obviously, "z" is not acceptable input and 100 is out of range as well, yet, no error is returned. I think a Color.isValid({format: 'oklch'}) would be a better api. I think it would be better to validate a known input, than having a validation that checked the input against ALL known color spaces.

ColorJS is amazing btw! Much resepct.

gandhiShepard avatar Aug 05 '24 18:08 gandhiShepard

Exceptions are not thrown for all invalid colors however. If using oklch("z" 100 230) the returned .toString value would be oklch(NaN 100 230). Obviously, "z" is not acceptable input and 100 is out of range as well, yet, no error is returned.

Interesting point. NaN is a valid coordinate value (corresponds to the CSS calc(NaN)), but perhaps we should not be treating all unparseable strings as equivalent to NaN.

I think a Color.isValid({format: 'oklch'}) would be a better api. I think it would be better to validate a known input, than having a validation that checked the input against ALL known color spaces.

There's a separate code path for functional formats and they zero in pretty quickly to the relevant color space. It would be helpful to know the use cases that prompted this. If it's just to facilitate fault tolerance, see #518, I wonder if that would be an acceptable solution?

ColorJS is amazing btw! Much resepct.

Thanks! <3

LeaVerou avatar Aug 05 '24 18:08 LeaVerou

I was trying to validate colors strings within an input while a user types.

gandhiShepard avatar Aug 06 '24 04:08 gandhiShepard

I'm curious why new Color("rgb(1000, 'echo', null)") throws an exception but new Color("srgb", [-1000, "echo", null]) does not. If I have these values separately rather than as a CSS string, how can I get the exception throwing behavior?

(My hacky idea of new Color(new Color("srgb", [-1000, "echo", null]).toString()) doesn't work because the invalid values are set to 0 in the string output of the inner Color.)

(Also agree that the library is awesome!)

bakert avatar Aug 21 '24 01:08 bakert