UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

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