Skip to content

Instantly share code, notes, and snippets.

@bilalafzal01
Created June 27, 2021 10:30
Show Gist options
  • Save bilalafzal01/cbdb7d2a9611cd1ef4f9ce3dae1b48c4 to your computer and use it in GitHub Desktop.
Save bilalafzal01/cbdb7d2a9611cd1ef4f9ce3dae1b48c4 to your computer and use it in GitHub Desktop.
Reusable Typescript validate function
// 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