shelving
Version:
Toolkit for using data in JavaScript.
40 lines (39 loc) • 1.51 kB
JavaScript
import { getDate, requireDateString } from "../util/date.js";
import { formatDate } from "../util/format.js";
import { roundStep } from "../util/number.js";
import { NULLABLE } from "./NullableSchema.js";
import { Schema } from "./Schema.js";
export class DateSchema extends Schema {
min;
max;
input;
step;
constructor({ one = "date", min, max, value, input = "date", step, ...options }) {
super({ one, title: "Date", value, ...options });
this.min = getDate(min);
this.max = getDate(max);
this.input = input;
this.step = step;
}
validate(value = this.value) {
const date = getDate(value);
if (!date)
throw value ? `Invalid ${this.one} format` : "Required";
const stepped = typeof this.step === "number" ? new Date(roundStep(date.getTime(), this.step)) : date;
if (this.min && stepped < this.min)
throw `Minimum ${this.format(this.stringify(this.min))}`;
if (this.max && stepped > this.max)
throw `Maximum ${this.format(this.stringify(this.max))}`;
return this.stringify(stepped);
}
stringify(value) {
return requireDateString(value);
}
format(value) {
return formatDate(value, undefined, this.format);
}
}
/** Valid date, e.g. `2005-09-12` (required because falsy values are invalid). */
export const DATE = new DateSchema({});
/** Valid date, e.g. `2005-09-12`, or `null` */
export const NULLABLE_DATE = NULLABLE(DATE);