Created
June 27, 2021 10:30
-
-
Save bilalafzal01/cbdb7d2a9611cd1ef4f9ce3dae1b48c4 to your computer and use it in GitHub Desktop.
Reusable Typescript validate function
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
// Validation | |
interface Validatable { | |
value: string | number; | |
required?: boolean; | |
minLength?: number; | |
maxLength?: number; | |
min?: number; | |
max?: number; | |
} | |
const validate = (validatableInput: Validatable): boolean => { | |
let isValid = true; | |
// check required | |
if (validatableInput.required) { | |
isValid = isValid && validatableInput.value.toString().trim().length !== 0; | |
} | |
// check min length | |
if ( | |
validatableInput.minLength != null && | |
typeof validatableInput.value === "string" | |
) { | |
isValid = | |
isValid && validatableInput.value.length > validatableInput.minLength; | |
} | |
// check max length | |
if ( | |
validatableInput.maxLength != null && | |
typeof validatableInput.value === "string" | |
) { | |
isValid = | |
isValid && validatableInput.value.length < validatableInput.maxLength; | |
} | |
// check min number | |
if ( | |
validatableInput.min != null && | |
typeof validatableInput.value === "number" | |
) { | |
isValid = isValid && validatableInput.value > validatableInput.min; | |
} | |
// check max number | |
if ( | |
validatableInput.max != null && | |
typeof validatableInput.value === "number" | |
) { | |
isValid = isValid && validatableInput.value < validatableInput.max; | |
} | |
return isValid; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment