diff --git a/src/vine/main.ts b/src/vine/main.ts index 9691cce..53f6c6d 100644 --- a/src/vine/main.ts +++ b/src/vine/main.ts @@ -14,6 +14,7 @@ import { SimpleMessagesProvider } from '../messages_provider/simple_messages_pro import { VineValidator } from './validator.js' import { fields, messages } from '../defaults.js' +import { ValidationError } from '../errors/validation_error.js' import { SimpleErrorReporter } from '../reporters/simple_error_reporter.js' import type { Infer, @@ -117,4 +118,35 @@ export class Vine extends SchemaBuilder { const validator = this.compile(options.schema) return validator.validate(options.data, options) } + + /** + * Validate data against a schema without throwing the + * "ValidationError" exception. Instead the validation + * errors are returned within the return value. + * + * ```ts + * await vine.tryValidate({ schema, data }) + * await vine.tryValidate({ schema, data, messages, fields }) + * + * await vine.tryValidate({ schema, data, messages, fields }, { + * errorReporter + * }) + * ``` + */ + tryValidate( + options: { + /** + * Schema to use for validation + */ + schema: Schema + + /** + * Data to validate + */ + data: any + } & ValidationOptions | undefined> + ): Promise<[ValidationError, null] | [null, Infer]> { + const validator = this.compile(options.schema) + return validator.tryValidate(options.data, options) + } } diff --git a/src/vine/validator.ts b/src/vine/validator.ts index 7f14d97..fdbf241 100644 --- a/src/vine/validator.ts +++ b/src/vine/validator.ts @@ -163,6 +163,19 @@ export class VineValidator< * Performs validation without throwing the validation * exception. Instead, the validation errors are * returned as the first argument. + * + * + * ```ts + * await validator.tryValidate(data) + * await validator.tryValidate(data, { meta: {} }) + * + * await validator.tryValidate(data, { + * meta: { userId: auth.user.id }, + * errorReporter, + * messagesProvider + * }) + * ``` + * */ async tryValidate( data: any,