Created
February 10, 2020 11:52
-
-
Save busypeoples/a3ba9d2218e7cb7eda923db40f505f42 to your computer and use it in GitHub Desktop.
Validation in TS
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> = (input: T) => ValidationResult<T, U>; | |
const mergeAll = <T, U>( | |
results: ValidationResult<T, U>[] | |
): ValidationResult<T, U> => | |
results.reduce((acc, a) => Object.assign(acc, a), {}); | |
const validate = <T, U = boolean | string>( | |
validations: Validation<T, U>[] | |
): Validation<T, U> => { | |
return fields => { | |
return mergeAll<T, U>(validations.map(validation => validation(fields))); | |
}; | |
}; | |
// Validators | |
const isGt4 = (input: number): boolean => input > 4; | |
const isGT8 = (input: number): boolean => input > 8; | |
const isEmpty = (input: string) => input.length === 0; | |
// specific validation function | |
const isUserNameDefined = (input: string) => (isEmpty(input) ? true : "Empty!"); | |
// Values | |
const fieldValues = { | |
a: 3, | |
b: 9, | |
c: "Test input" | |
}; | |
type FieldValues = typeof fieldValues; | |
const validateForm = validate<FieldValues>([ | |
({ a }: FieldValues) => ({ | |
a: isGt4(a) ? true : "Needs to be greater than 4" | |
}), | |
({ b }: FieldValues) => ({ | |
b: isGT8(b) ? true : "Needs to be greater than 8" | |
}) | |
]); | |
const validateOtherForm = validate< | |
FieldValues, | |
boolean | string | (boolean | string)[] | |
>([ | |
({ a }) => ({ a: [isGt4(a) ? true : "Needs to be greater than 4!"] }), | |
({ c }) => ({ c: isUserNameDefined(c) }) | |
]); | |
console.log(validateForm(fieldValues)); | |
// {a: "Needs to be greater than 4", b: true} | |
console.log(validateOtherForm(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