@ticatec/web-bean-validator
Version:
A TypeScript/JavaScript library for rule-based entity validation with boundary checking for strings, numbers, dates, enums, objects, and arrays.
45 lines (44 loc) • 1.85 kB
JavaScript
import BaseValidator from "./BaseValidator";
import dayjs from "dayjs";
import i18nRes from "../i18nRes";
const formatDate = (d, dateFmt = 'YYYY-MM-DD') => {
return dayjs(d).format(dateFmt);
};
export default class DateValidator extends BaseValidator {
constructor(field, options) {
super(field, options);
this.from = options === null || options === void 0 ? void 0 : options.from;
this.to = options === null || options === void 0 ? void 0 : options.to;
this.maxDaysAfter = options === null || options === void 0 ? void 0 : options.maxDaysAfter;
this.maxDaysBefore = options === null || options === void 0 ? void 0 : options.maxDaysBefore;
}
checkField(value, result) {
let now = (new Date()).getTime();
let latestDate = this.maxDaysAfter != null ? new Date(now + (this.maxDaysAfter + 1) * 86400000) : this.to;
let earliestDate = this.maxDaysBefore != null ? new Date(now - this.maxDaysBefore * 86400000) : this.from;
if (earliestDate && earliestDate > value) {
result.setError(this.field, this.formatErrorMessage(i18nRes.validation.earliestDate, {
field: this.name,
date: formatDate(earliestDate)
}));
return false;
}
if (latestDate && latestDate < value) {
result.setError(this.field, this.formatErrorMessage(i18nRes.validation.finalDate, {
field: this.name,
date: formatDate(latestDate)
}));
return false;
}
return true;
}
checkType(value) {
if (typeof value == "string") {
value = new Date(value);
}
else if (typeof value == "number") {
value = new Date(value);
}
return value instanceof Date ? value : null;
}
}