UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

18 lines (17 loc) 713 B
import { ThroughSchema } from "./ThroughSchema.js"; /** Validate a value of a specific type or `null`. */ export class NullableSchema extends ThroughSchema { constructor({ value = null, ...options }) { super({ value, ...options }); } validate(unsafeValue = this.value) { if (unsafeValue === null || unsafeValue === undefined || unsafeValue === "" || Number.isNaN(unsafeValue)) return null; return super.validate(unsafeValue); } format(value) { return value === null ? `No ${this.source.one}` : super.format(value); } } /** Create a new nullable schema from a source schema. */ export const NULLABLE = (source) => new NullableSchema({ source });