-
-
Save tanepiper/e3a32cd9bb7d88f642e5ea7398267bcc to your computer and use it in GitHub Desktop.
Validation in TS (version 2)
This file contains hidden or 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