Validation rules
Lucid adds validation rules to VineJS to use in your schemas. Under the hood, it registers a provider in your AdonisJS application that extends VineJS rules. You can read more in the AdonisJS docs and VineJS docs.
You can use these rules directly from your VineJS schema. For example, the unique
rule:
import vine from '@vinejs/vine'
const schema = vine.object({
email: vine
.string()
.unique({
table: 'users',
column: 'email',
}),
})
Unique
Ensure the value is unique (does not exists) inside a given database table and column.
The rule is a macro for VineString
and VineNumber
, so you can use it after vine.string()
or vine.number()
.
You may either pass a callback to query the database directly, or an object:
- The callback must return
true
if the value is unique (does not exist), orfalse
if the value already exists. - You may also pass an options object to specify the table and column.
// Usage with callback
const schema = vine.object({
email: vine
.string()
.unique((db, value) => {
const row = await db.from('users').where('email', value).first()
return row === null
}),
})
// Usage with options
const schema = vine.object({
email: vine
.string()
.unique({ table: 'users', column: 'email' }),
})
You may also use your Lucid model directly inside the callback:
const schema = vine.object({
email: vine
.string()
.unique((_, value) => {
const row = await User.findBy('email', value)
return row ? false : true
}),
})
Exists
Ensure the value exists inside a given database table and column. This is the inverse of the unique rule.
The rule is also a macro for VineString
and VineNumber
, so you can use it after vine.string()
or vine.number()
.
You may either pass a callback to query the database directly, or an object:
- The callback must return
true
if the value exists,false
otherwise. - You may also pass an options object to specify the table and column.
// Usage with callback
const schema = vine.object({
slug: vine
.string()
.exists((db, value) => {
const row = await db.from('categories').where('slug', value).first()
return row ? true : false
}),
})
// Usage with options
const schema = vine.object({
slug: vine
.string()
.exists({ table: 'categories', column: 'slug' }),
})