nowjs-core
Version:
NowCanDo Javascript Core [nowjs-core] is a library written by TypeScript code maintains under Apache 2.0 licence
62 lines (61 loc) • 2.82 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../index");
exports.VALIDATOR_INRANGE_METADATA_KEY = Symbol('validation:validator:isInRange');
exports.VALIDATOR_INLENGTH_METADATA_KEY = Symbol('validation:validator:isInLength');
function isInRange(min, max, errorMessage) {
return (target, propertyKey, descriptor) => {
const original = descriptor.value;
Reflect.defineMetadata(exports.VALIDATOR_INRANGE_METADATA_KEY, null, target, propertyKey);
Reflect.defineMetadata(index_1.VALIDATOR_METADATA_KEY, new InRangeValidator(min, max, errorMessage), target, propertyKey);
};
}
exports.isInRange = isInRange;
function isInLength(min, max, errorMessage) {
return (target, propertyKey, descriptor) => {
const original = descriptor.value;
Reflect.defineMetadata(exports.VALIDATOR_INLENGTH_METADATA_KEY, null, target, propertyKey);
Reflect.defineMetadata(index_1.VALIDATOR_METADATA_KEY, new InRangeValidator(min, max, errorMessage), target, propertyKey);
};
}
exports.isInLength = isInLength;
class InRangeValidatorBase extends index_1.ValidatorBase {
constructor(name, min, max, errorMessage = 'The value of ${DisplayName} must between as min: ${Min} and max : ${Max}.') {
super(name, errorMessage);
this.min = min;
this.max = max;
}
get Min() {
return this.min;
}
get Max() {
return this.max;
}
validate(context) {
if (context.Value === undefined || context.Value === null) {
return Promise.resolve(true);
}
if (typeof context.Value === 'string') {
if (context.Value.length < this.min || context.Value.length > this.max) {
return Promise.reject(new index_1.ValidatorException(this.Name, context.Target, context.PropertyName, this.formatErrorMessage(context)));
}
}
else if (context.Value < this.min || context.Value > this.max) {
return Promise.reject(new index_1.ValidatorException(this.Name, context.Target, context.PropertyName, this.formatErrorMessage(context)));
}
return Promise.resolve(true);
}
}
exports.InRangeValidatorBase = InRangeValidatorBase;
class InRangeValidator extends InRangeValidatorBase {
constructor(min, max, errorMessage = 'The value of ${DisplayName} must between as min: ${Min} and max : ${Max}.') {
super('InRange', min, max, errorMessage);
}
}
exports.InRangeValidator = InRangeValidator;
class InLengthValidator extends InRangeValidatorBase {
constructor(min, max, errorMessage = 'The value of ${DisplayName} must between as min: ${Min} and max : ${Max}.') {
super('InLength', min, max, errorMessage);
}
}
exports.InLengthValidator = InLengthValidator;