Skip to content

Instantly share code, notes, and snippets.

@busypeoples
Created February 10, 2020 14:50
Show Gist options
  • Save busypeoples/eebd1f893671959162df97cc8a6292e0 to your computer and use it in GitHub Desktop.
Save busypeoples/eebd1f893671959162df97cc8a6292e0 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