Skip to content

Commit

Permalink
feat: add tryValidate method to Vine
Browse files Browse the repository at this point in the history
  • Loading branch information
Harminder Virk authored and Harminder Virk committed Jun 2, 2024
1 parent cebb8e0 commit a70ff38
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/vine/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<Schema extends SchemaTypes>(
options: {
/**
* Schema to use for validation
*/
schema: Schema

/**
* Data to validate
*/
data: any
} & ValidationOptions<Record<string, any> | undefined>
): Promise<[ValidationError, null] | [null, Infer<Schema>]> {
const validator = this.compile(options.schema)
return validator.tryValidate(options.data, options)
}
}
13 changes: 13 additions & 0 deletions src/vine/validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit a70ff38

Please sign in to comment.