UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

27 lines (26 loc) 1.08 kB
import { ValueFeedback } from "../feedback/Feedback.js"; import { getFileExtension } from "../util/file.js"; import { isProp } from "../util/object.js"; import { OPTIONAL } from "./OptionalSchema.js"; import { StringSchema } from "./StringSchema.js"; /** Validate a file name matching one or more extensions. */ export class FileSchema extends StringSchema { types; constructor({ types, title = "File", ...options }) { super({ title, ...options }); this.types = types; } validate(unsafeValue = this.value) { const path = super.validate(unsafeValue); const extension = getFileExtension(path); if (!extension) throw new ValueFeedback("Must be file name with extension", unsafeValue); if (this.types && !isProp(this.types, extension)) throw new ValueFeedback("Invalid file type", extension); return path; } } /** Valid file, e.g. `file.txt` */ export const FILE = new FileSchema({}); /** Valid optional file, e.g. `file.txt`, or `null` */ export const OPTIONAL_FILE = OPTIONAL(FILE);