UNPKG

nowjs-core

Version:

NowCanDo Javascript Core [nowjs-core] is a library written by TypeScript code maintains under Apache 2.0 licence

59 lines (58 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const index_1 = require("../index"); exports.VALIDATOR_COMPARETO_METADATA_KEY = Symbol('validation:validator:compareTo'); function compareTo(style, anotherTarget, anotherPropertyName = '', errorMessage) { return (target, propertyKey, descriptor) => { const original = descriptor.value; Reflect.defineMetadata(exports.VALIDATOR_COMPARETO_METADATA_KEY, null, target, propertyKey); Reflect.defineMetadata(index_1.VALIDATOR_METADATA_KEY, new CompareToValidator(style, anotherTarget, anotherPropertyName, errorMessage), target, propertyKey); }; } exports.compareTo = compareTo; class CompareToValidatorBase extends index_1.ValidatorBase { constructor(name, style, anotherTarget, anotherPropertyName = '', errorMessage = 'The value of ${DisplayName} must ${style} .') { super(name, errorMessage); this.style = style; this.anotherTarget = anotherTarget; this.anotherPropertyName = anotherPropertyName; } get Style() { return this.style; } isMatched(context, another) { switch (this.style) { case 'equal': return context.Value === another.Value; case 'greater': return context.Value > another.Value; case 'lesser': return context.Value < another.Value; case 'greatOrEqual': return context.Value >= another.Value; case 'lessOrEqual': return context.Value <= another.Value; case 'notEqual': return context.Value !== another.Value; default: return true; } } validate(context) { if (context.Value === undefined || context.Value === null) { return Promise.resolve(true); } const anotherContext = new index_1.ValidationContext(this.anotherTarget, this.anotherPropertyName); if (!this.isMatched(context, anotherContext)) { return Promise.reject(new index_1.ValidatorException(this.Name, context.Target, context.PropertyName, this.formatErrorMessage(context))); } return Promise.resolve(true); } } exports.CompareToValidatorBase = CompareToValidatorBase; class CompareToValidator extends CompareToValidatorBase { constructor(style, anotherTarget, anotherPropertyName = '', errorMessage = 'The value of ${DisplayName} must ${style} .') { super('CompareTo', style, anotherTarget, anotherPropertyName, errorMessage); } } exports.CompareToValidator = CompareToValidator;