import { ALLOWED_DATA_UNITS } from '../constants/validation' ; import { parseInterval } from './parse_interval' ; import { isPopulatedObject } from './object_utils' ; param maxLength export function maxLengthValidator ( maxLength ) { return ( value ) => value && value . length > maxLength ? { maxLength : { requiredLength : maxLength , actualLength : value . length , } , } : null ; } param pattern export function patternValidator ( pattern ) { return ( value ) => pattern . test ( value ) ? null : { pattern : { matchPattern : pattern . toString ( ) , } , } ; } param validators export function composeValidators ( ... validators ) { return ( value ) => { const validationResult = validators . reduce ( ( acc , validator ) => { return { ... acc , ... ( validator ( value ) || { } ) , } ; } , { } ) ; return Object . keys ( validationResult ) . length > 0 ? validationResult : null ; } ; } export function requiredValidator ( ) { return < T extends string > ( value ) => { return value === '' || value === undefined || value === null ? { required : true } : null ; } ; } export type ValidationResult = Record < string , any > | null ; export type MemoryInputValidatorResult = { invalidUnits : { allowedUnits : string ; } ; } | null ; export function memoryInputValidator ( allowedUnits = ALLOWED_DATA_UNITS ) { return < T > ( value ) => { if ( typeof value !== 'string' || value === '' ) { return null ; } const regexp = new RegExp ( `\\d+(${ allowedUnits . join ( '|' ) })$` , 'i' ) ; return regexp . test ( value . trim ( ) ) ? null : { invalidUnits : { allowedUnits : allowedUnits . join ( ', ' ) } } ; } ; } export function timeIntervalInputValidator ( ) { return ( value ) => { if ( value === '' ) { return null ; } const r = parseInterval ( value ) ; if ( r === null ) { return { invalidTimeInterval : true , } ; } return null ; } ; } export interface NumberValidationResult { min : boolean ; max : boolean ; } export function numberValidator ( conditions ? ) { if ( conditions ?. min !== undefined && conditions . max !== undefined && conditions . min > conditions . max ) { throw new Error ( 'Invalid validator conditions' ) ; } return ( value ) : NumberValidationResult | null => { const result = { } as NumberValidationResult ; if ( conditions ?. min !== undefined && value < conditions . min ) { result . min = true ; } if ( conditions ?. max !== undefined && value > conditions . max ) { result . max = true ; } if ( isPopulatedObject ( result ) ) { return result ; } return null ; } ; }