import { isLength , isEmpty } from 'validator' ; import { ruleMap } from './rules' ; interface IOptions { message : string ; value : string | number | object ; } class Validators { private rules : { [ field ] : { [ rule ] : IOptions ; } ; } ; constructor ( ) { this . rules = { } ; } public setRule ( field , rule , options ) { const previousRules = this . getRules ( field ) ; this . rules = { ... this . rules , [ field ] : { ... previousRules , [ rule ] : { ... previousRules [ rule ] , ... options } } } ; } public hasRule ( name ) { return ! ! this . rules [ name ] ; } public getRules ( name ) { return this . rules [ name ] || { } ; } public validateRule ( field , value ) { const fieldRules = this . getRules ( field ) ; return Object . keys ( fieldRules ) . reduce ( ( acc , rule ) => { if ( acc ) { return acc ; } const validator = ruleMap [ rule ] ; if ( validator ) { return validator ( value , fieldRules [ rule ] . message , fieldRules [ rule ] . value ) ; } return undefined ; } , undefined ) ; } } export default Validators ;