colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
32.64k stars 1.13k forks source link

.color() function to validate that a string is a valid color. #3633

Open BenjaminLindberg opened 1 month ago

BenjaminLindberg commented 1 month ago

Hi, I would want a .color() function that you append on a z.string() to validate that it's a valid color.

This feature would be useful in many cases. For example if you want to make sure that payload coming from client/frontend contains valid color codes, directly with zod.

I believe that by default .color() should accept all of the standard forms of colors eg:

But also offer some way to only accept (a) certain color type(s), alternatively filter out unwanted color types.

Might not be that of a realistic feature, but some way to convert the payload to a specified color type. For example if a hex value gets inputted, it gets converted to the specified type, rgb for example . I know this might cause some inaccuracy when converting from certain types to others, but still a feature i would want.

I am open to make this feature myself later on if it gets decided that it's a needed feature.

eswarty commented 1 month ago

Hello! Just a suggestion that you can use z.string().refine() to implement a custom color validator. Maybe something simple like:

import color from "color-string";

export function colorValidator(val: string) {
  try {
    return color.get(val) != null;
  } catch {
    return false;
  }
}

const validColorSchema = z.string().refine(colorValidator);
validColorSchema.parse("#FFF");
BenjaminLindberg commented 3 weeks ago

@eswarty thanks! Ill definitely try that out. Using .regex would also work I believe.