UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

30 lines (29 loc) 1.22 kB
import { ValueFeedback } from "../feedback/Feedback.js"; import { getDate, requireYMD } from "../util/date.js"; import { formatDate } from "../util/format.js"; import { OPTIONAL } from "./OptionalSchema.js"; import { Schema } from "./Schema.js"; /** Define a valid date in YMD format, e.g. `2005-09-12` */ export class DateSchema extends Schema { min; max; constructor({ min, max, title = "Date", value = "now", ...options }) { super({ title, value, ...options }); this.min = getDate(min); this.max = getDate(max); } validate(value = this.value) { const date = getDate(value); if (!date) throw new ValueFeedback(value ? "Invalid date" : "Required", value); if (this.min && date < this.min) throw new ValueFeedback(`Minimum ${formatDate(this.min)}`, date); if (this.max && date > this.max) throw new ValueFeedback(`Maximum ${formatDate(this.max)}`, date); return requireYMD(date); } } /** 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 OPTIONAL_DATE = OPTIONAL(DATE);