Open BenjaminLindberg opened 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");
@eswarty thanks! Ill definitely try that out. Using .regex would also work I believe.
Hi, I would want a
.color()
function that you append on az.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:green
coral
steel blue
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.