export const validatorStack = {}; export const inputStack = new WeakMap(); export class Class{ static get _validators(){ return validatorStack; } /* (1) Push a new Format * * @_format Format name * @_validator Format callback * @_error Error message * * @return pushed Whether the validator has been pushed * ---------------------------------------------------------*/ static pushFormat(_format=null, _validator=null, _error='error'){ /* (1) Error: invalid _format */ if( typeof _format !== 'string' ) return false; /* (2) Error: invalid _validator */ if( !(_validator instanceof Function) ) return false; /* (3) Store validator */ Class._validators[_format] = { error: _error, validator: _validator }; return true; } /* (1) Pop an existing Format * * @_format Format name * * @return popped Whether the validator has been popped * ---------------------------------------------------------*/ static popFormat(_format=null){ /* (1) Error: invalid _format */ if( typeof _format !== 'string' ) return false; /* (2) Error: _validator not found */ if( Class._validators[_format] == null ) return false; /* (3) Remove validator */ delete Class._validators[_format]; return true; } /* (2) Builds an validat-able input * * @_format Existing validator name * @_default [OPT] Mutable input default value (default to NULL) * ---------------------------------------------------------*/ constructor(_format, _default=null){ /* (1) Store fields (default value) */ this.mutable = _default; /* (2) Store _format in STATIC inputStack */ inputStack.set(this, { format: _format }); } /* (3) Checks if the _mutable has a current valid value * * @return valid Whether the _mutable is valid or not * ---------------------------------------------------------*/ is_valid(){ // 1. Extract validator name let format = inputStack.get(this).format; // 2. Dispatch validation return validatorStack[format].validator( this.mutable ); } /* (3) Get current error message * * @return NULL if is_valid() * ---------------------------------------------------------*/ get error(){ // 1. NULL if valid if( this.is_valid() ) return ''; // 2. Extract validator name let format = inputStack.get(this).format; // 3. Dispatch validation return validatorStack[format].error; } }