Skip to content

Instantly share code, notes, and snippets.

@Arsfiqball
Created July 27, 2019 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arsfiqball/b922c62edcdc77f11fd1925c52e9eb7f to your computer and use it in GitHub Desktop.
Save Arsfiqball/b922c62edcdc77f11fd1925c52e9eb7f to your computer and use it in GitHub Desktop.
Validate unique value of database using knex.js and validate.js
const assert = require('assert')
const validate = require('validate.js')
const db = require('./db') // instance of knex
// custom validation
validate.validators.unique = function (value, options, key) {
assert.ok(!!options.table)
assert.ok(!!options.column)
assert.ok(!!options.db)
return options
.db(options.table)
.where(options.column, value)
.first(options.column)
.then(row => Promise.resolve(row ? `${key} is already used` : undefined))
.catch(console.error)
}
// usage
const constraints = {
username: {
unique: {
table: 'users',
column: 'username',
db: db
},
}
}
validate
.async({ username: 'someone' }, constraints)
.then(() => console.log('ok'))
.catch(err => console.log(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment