Created
February 10, 2020 14:50
-
-
Save busypeoples/eebd1f893671959162df97cc8a6292e0 to your computer and use it in GitHub Desktop.
Validation in TS (version 2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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