adonis validator exists 1

adonis validator exists

import { schema, rules } from '@ioc:Adonis/Core/Validator'

{
  slug: schema.string({}, [
    rules.exists({ table: 'categories', column: 'slug' })
  ])
}

Here is what the above code is Doing:
1. The `slug` field is defined as a string.
2. The `exists` rule is used to check if the value exists in the `slug` column of the `categories` table.

The `exists` rule is a combination of the `unique` and `exists` rules. It checks if the value exists in the database and is not associated with the current record.

## Using the `exists` rule

The `exists` rule is a combination of the `unique` and `exists` rules. It checks if the value exists in the database and is not associated with the current record.

### Using the `exists` rule

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core/Validator’

{
slug: schema.string({}, [
rules.exists({ table: ‘categories’, column: ‘slug’ })
])
}
“`

### Using the `exists` rule with custom error message

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core/Validator’

{
slug: schema.string({}, [
rules.exists({
table: ‘categories’,
column: ‘slug’,
message: ‘The slug is already taken’
})
])
}
“`

### Using the `exists` rule with custom error message as a method

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core/Validator’

{
slug: schema.string({}, [
rules.exists((value, _, message) => {
return message.error(‘The slug is already taken’)
})
])
}
“`

### Using the `exists` rule with custom error message as a method and custom options

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core/Validator’

{
slug: schema.string({}, [
rules.exists((value, _, message, { table, column }) => {
return message.error(`The ${column} is already taken`)
}, {
table: ‘categories’,
column: ‘slug’
})
])
}
“`

## Using the `existsNot` rule

The `existsNot` rule is a combination of the `unique` and `exists` rules. It checks if the value does not exists in the database.

### Using the `existsNot` rule

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core/Validator’

{
slug: schema.string({}, [
rules.existsNot({ table: ‘categories’, column: ‘slug’ })
])
}
“`

### Using the `existsNot` rule with custom error message

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core/Validator’

{
slug: schema.string({}, [
rules.existsNot({
table: ‘categories’,
column: ‘slug’,
message: ‘The slug is already taken’
})
])
}
“`

### Using the `existsNot` rule with custom error message as a method

“`ts
import { schema, rules } from ‘@ioc:Adonis/Core

Similar Posts