richardscarrott / ok-computer

λ "Functions all the way down" data validation for JavaScript and TypeScript.
MIT License
79 stars 0 forks source link

New validators #3

Open richardscarrott opened 2 years ago

richardscarrott commented 2 years ago
const uppercase = create(
  value => typeof value === 'string' && value.toUpperCase() === value
)('Expected uppercase string');

const lowercase = create(
  value => typeof value === 'string' && value.toLowerCase() === value
)('Expected lowercase string');
richardscarrott commented 2 years ago
const minmax = (minValue: number, maxValue: number = minValue) => err(and(min(minValue), max(maxValue)), `Expected number between ${minValue} and ${maxValue}`);
richardscarrott commented 2 years ago
const truthy = create(value => !!value)('Expected truthy value');
const falsy = create(value => !value)('Expected falsy value');
richardscarrott commented 2 years ago
// `like` or `objectLike` or `looseObject` or `objectWith` or `objectContaining`
const like = (validators) => object(validators, { allowUnknown: true });
richardscarrott commented 2 years ago
const trimmed = create(
  (value) => typeof value === "string" && value === value.trim()
)("Expected trimmed string");
richardscarrott commented 2 years ago
const any = create(() => true)('Expected any');

Could be useful when using array and object, e.g.

// Don't really care what's in the `errors` array or `headers` property, but don't want to loosen the response validator `allowUnknown`.
const gqlResponse = object({
   data: object({ id: string }),
   errors: or(undef, array(any)),
   headers: any
});