nope-validator
Version:
Fast and simple JS validator
88 lines (83 loc) • 3.05 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var _tslib = require('./_virtual/_tslib.js');
var NopePrimitive = require('./NopePrimitive.js');
var NopeReference = require('./NopeReference.js');
var NopeDate = /** @class */ (function (_super) {
_tslib.__extends(NopeDate, _super);
function NopeDate(message) {
if (message === void 0) { message = 'The field is not a valid date'; }
var _this = _super.call(this) || this;
_this._type = 'object';
_this.message = message;
return _this;
}
NopeDate.prototype.before = function (beforeDate, message) {
var _this = this;
if (message === void 0) { message = "Date must be before ".concat(beforeDate.toString()); }
var rule = function (entry, context) {
if (_this.isEmpty(entry)) {
return;
}
var resolvedBeforeDate = beforeDate instanceof NopeReference.NopeReference && context ? context[beforeDate.key] : beforeDate;
if (new Date(entry) >= new Date(resolvedBeforeDate)) {
return message;
}
};
return this.test(rule);
};
NopeDate.prototype.after = function (afterDate, message) {
var _this = this;
if (message === void 0) { message = "Date must be after ".concat(afterDate); }
var rule = function (entry, context) {
if (_this.isEmpty(entry)) {
return;
}
var resolvedAfterDate = afterDate instanceof NopeReference.NopeReference && context ? context[afterDate.key] : afterDate;
if (new Date(entry) <= new Date(resolvedAfterDate)) {
return message;
}
};
return this.test(rule);
};
NopeDate.prototype.parseDate = function (entry) {
var value = entry;
if (this.isEmpty(entry) || entry instanceof Date) {
value = entry;
}
else if (!isNaN(+new Date(entry))) {
value = new Date(entry);
}
else {
var ms = new Date(entry);
if (isNaN(+ms)) {
throw this.message;
}
value = new Date(ms);
}
return value;
};
NopeDate.prototype.validate = function (entry, context) {
var value;
try {
value = this.parseDate(entry);
}
catch (error) {
return error;
}
return _super.prototype.validate.call(this, value, context);
};
NopeDate.prototype.validateAsync = function (entry, context) {
var value;
try {
value = this.parseDate(entry);
}
catch (error) {
return Promise.resolve(error);
}
return _super.prototype.validateAsync.call(this, value, context);
};
return NopeDate;
}(NopePrimitive.NopePrimitive));
exports.NopeDate = NopeDate;
//# sourceMappingURL=NopeDate.js.map