Skip to content

Commit

Permalink
feat: implement Array validator
Browse files Browse the repository at this point in the history
  • Loading branch information
IamSebastianDev committed Dec 4, 2022
1 parent b464576 commit c4b909f
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
37 changes: 37 additions & 0 deletions src/lib/Validators/IsArray.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/** @format */

import { ArrayValidatorInit, ValidatorFunction } from '../../types';
import { FlotsamValidationError } from '../../utils';

export const IsArray = (validationRules?: ArrayValidatorInit): ValidatorFunction => {
const { min, max, items } = validationRules || {};
return (value: unknown, propertyName: string) => {
if (!Array.isArray(value)) {
throw new FlotsamValidationError(
`Expected property '${propertyName}' to be of type 'Array'. Found property to be of type '${typeof value}' instead.`
);
}

const { length } = value;

if (min && length < min) {
throw new FlotsamValidationError(
`Expected property '${propertyName}' to be at least of length '${min}'. Found length '${length}' instead.`
);
}

if (max && length > max) {
throw new FlotsamValidationError(
`Expected property '${propertyName}' to be at max of length '${max}'. Found length '${length}' instead.`
);
}

if (items && !value.every((item) => typeof item === items)) {
throw new FlotsamValidationError(
`Expected property '${propertyName}' to contain only elements of type ${items}`
);
}

return true;
};
};
9 changes: 9 additions & 0 deletions src/types/ArrayValidatorInit.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** @format */

import type { Primitive } from './Primitive';

export type ArrayValidatorInit = {
min?: number;
max?: number;
items?: Primitive;
};
2 changes: 1 addition & 1 deletion src/types/Primitive.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
/** @format */

type Primitive = 'string' | 'number' | 'object' | 'function' | 'bigint' | 'symbol' | 'undefined' | 'boolean';
export type Primitive = 'string' | 'number' | 'object' | 'function' | 'bigint' | 'symbol' | 'undefined' | 'boolean';
1 change: 1 addition & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export type { FindByProperty } from './FindByProperty';
export type { ValidatorFunction } from './ValidatorFunction';
export type { Validator } from './Validator';
export type { Primitive } from './Primitive';
export type { ArrayValidatorInit } from './ArrayValidatorInit';

0 comments on commit c4b909f

Please sign in to comment.