diff --git a/src/validators/BaseValidator.ts b/src/validators/BaseValidator.ts index 1bd817e7..68219add 100644 --- a/src/validators/BaseValidator.ts +++ b/src/validators/BaseValidator.ts @@ -12,6 +12,7 @@ import type { IConstraint } from '../constraints/base/IConstraint'; import type { BaseError } from '../lib/errors/BaseError'; export abstract class BaseValidator { + public description?: string; protected parent?: object; protected constraints: readonly IConstraint[] = []; protected isValidationEnabled: boolean | (() => boolean) | null = null; @@ -69,6 +70,12 @@ export abstract class BaseValidator { return this.addConstraint(whenConstraint(key, options, this as unknown as This)); } + public describe(description: string): this { + const clone = this.clone(); + clone.description = description; + return clone; + } + public run(value: unknown): Result { let result = this.handle(value) as Result; if (result.isErr()) return result; diff --git a/tests/validators/base.test.ts b/tests/validators/base.test.ts index 4d141752..5d450c93 100644 --- a/tests/validators/base.test.ts +++ b/tests/validators/base.test.ts @@ -2,6 +2,14 @@ import { CombinedError, ExpectedValidationError, Result, s, ValidationError } fr import { expectClonedValidator, expectError, expectModifiedClonedValidator } from '../common/macros/comparators'; describe('BaseValidator', () => { + describe('description', () => { + test('GIVEN a validator THEN returns the description', () => { + const validator = s.string.describe('The name of the user'); + + expect(validator.description).toBe('The name of the user'); + }); + }); + describe('is', () => { test("GIVEN any value THEN it's narrowed to schema type", () => { const predicate = s.string;