shelving
Version:
Toolkit for using data in JavaScript.
40 lines (39 loc) • 1.45 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 = "now", 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 date" : "Required";
const rounded = typeof this.step === "number" ? new Date(roundStep(date.getTime(), this.step)) : date;
if (this.min && rounded < this.min)
throw `Minimum ${this.format(this.min)}`;
if (this.max && rounded > this.max)
throw `Maximum ${this.format(this.max)}`;
return this.stringify(rounded);
}
stringify(value) {
return requireDateString(value);
}
format(value) {
return formatDate(value);
}
}
/** 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);