Skip to content

Instantly share code, notes, and snippets.

@tanepiper
Forked from busypeoples/validation.ts
Created February 10, 2020 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanepiper/e3a32cd9bb7d88f642e5ea7398267bcc to your computer and use it in GitHub Desktop.
Save tanepiper/e3a32cd9bb7d88f642e5ea7398267bcc to your computer and use it in GitHub Desktop.
Validation in TS (version 2)
type ValidationResult<T, U> = Partial<{ [Key in keyof T]: U }>;
type Validation<T, U> = (fields: T) => ValidationResult<T, U>;
const validate = <T, U = boolean | string>(
validations: Validation<T, U>[],
fields: T
): ValidationResult<T, U> =>
validations
.map(validation => validation(fields))
.reduce((acc, a) => Object.assign(acc, a), {});
// Example
// Validators
const isGt4 = (input: number): boolean => input > 4;
const isGT8 = (input: number): boolean => input > 8;
const isEmpty = (input: string) => input.length === 0;
// Specific validation functions
const isUserNameDefined = (input: string) => (isEmpty(input) ? true : "Empty!");
// Values
const fieldValues = {
a: 3,
b: 9,
c: "Test input"
};
type FieldValues = typeof fieldValues;
const validationRules = [
({ a }: FieldValues) => ({
a: isGt4(a) ? true : "Needs to be greater than 4"
}),
({ b }: FieldValues) => ({
b: isGT8(b) ? true : "Needs to be greater than 8"
})
];
console.log(validate<FieldValues>(validationRules, fieldValues));
// {a: "Needs to be greater than 4", b: true}
console.log(
validate<FieldValues, boolean | string | (boolean | string)[]>(
[
({ a }) => ({ a: [isGt4(a) ? true : "Needs to be greater than 4!"] }),
({ c }) => ({ c: isUserNameDefined(c) })
],
fieldValues
)
);
// {a: ["Needs to be greater than 4!"], c: "Empty!"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment