import {ValidationResult, ValidatorFunction} from "./types"; export namespace Arr { /** Requires the input value to be an array. */ export function is(fieldName: string, inputValue: any): ValidationResult { if ( Array.isArray(inputValue) ) { return { valid: true } } return { valid: false, message: 'must be an array' } } /** Requires the values in the input value array to be distinct. */ export function distinct(fieldName: string, inputValue: any): ValidationResult { const arr = is(fieldName, inputValue) if ( !arr.valid ) return arr if ( (new Set(inputValue)).size === inputValue.length ) { return { valid: true } } return { valid: false, message: 'must not contain duplicate values' } } /** * Builds a validator function that requires the input array to contain the given value. * @param value */ export function includes(value: any): ValidatorFunction { return function includes(fieldName: string, inputValue: any): ValidationResult { const arr = is(fieldName, inputValue) if ( !arr.valid ) return arr if ( inputValue.includes(value) ) { return { valid: true } } return { valid: false, message: `must include ${value}` } } } /** * Builds a validator function that requires the input array NOT to contain the given value. * @param value */ export function excludes(value: any): ValidatorFunction { return function excludes(fieldName: string, inputValue: any): ValidationResult { const arr = is(fieldName, inputValue) if ( !arr.valid ) return arr if ( !inputValue.includes(value) ) { return { valid: true } } return { valid: false, message: `must not include ${value}` } } } /** * Builds a validator function that requires the input array to have exactly `len` many entries. * @param len */ export function length(len: number): ValidatorFunction { return function length(fieldName: string, inputValue: any): ValidationResult { const arr = is(fieldName, inputValue) if ( !arr.valid ) return arr if ( inputValue.length === len ) { return { valid: true } } return { valid: false, message: `must be exactly of length ${len}` } } } /** * Builds a validator function that requires the input array to have at least `len` many entries. * @param len */ export function lengthMin(len: number): ValidatorFunction { return function lengthMin(fieldName: string, inputValue: any): ValidationResult { const arr = is(fieldName, inputValue) if ( !arr.valid ) return arr if ( inputValue.length >= len ) { return { valid: true } } return { valid: false, message: `must be at least length ${len}` } } } /** * Builds a validator function that requires the input array to have at most `len` many entries. * @param len */ export function lengthMax(len: number): ValidatorFunction { return function lengthMax(fieldName: string, inputValue: any): ValidationResult { const arr = is(fieldName, inputValue) if ( !arr.valid ) return arr if ( inputValue.length <= len ) { return { valid: true } } return { valid: false, message: `must be at most length ${len}` } } } }