UNPKG

fortify-schema

Version:

TypeScript interface-like schema validation system that's easier to use than Zod

71 lines (67 loc) 2 kB
'use strict'; var ConditionalThen = require('./ConditionalThen.js'); /** * Builder for single field conditional validation with TypeScript inference */ class ConditionalBuilder { constructor(fieldName) { this.fieldName = fieldName; this.conditions = []; this.defaultSchema = null; } /** * Check if field equals specific value */ is(value) { return new ConditionalThen.ConditionalThen(this, (fieldValue) => fieldValue === value); } /** * Check if field does not equal specific value */ isNot(value) { return new ConditionalThen.ConditionalThen(this, (fieldValue) => fieldValue !== value); } /** * Check if field exists (not null/undefined) */ exists() { return new ConditionalThen.ConditionalThen(this, (fieldValue) => fieldValue != null); } /** * Check if field matches pattern */ matches(pattern) { return new ConditionalThen.ConditionalThen(this, (fieldValue) => typeof fieldValue === "string" && pattern.test(fieldValue)); } /** * Check if field is in array of values */ in(values) { return new ConditionalThen.ConditionalThen(this, (fieldValue) => values.includes(fieldValue)); } /** * Custom condition function */ when(condition) { return new ConditionalThen.ConditionalThen(this, condition); } addCondition(condition, schema) { this.conditions.push({ condition, schema }); return this; } default(schema) { this.defaultSchema = schema; return this.build(); } build() { // Return a special object that the validation engine can recognize return { __conditional: true, fieldName: this.fieldName, conditions: this.conditions, default: this.defaultSchema }; } } exports.ConditionalBuilder = ConditionalBuilder; //# sourceMappingURL=ConditionalBuilder.js.map