0.0.4 • Published 8 years ago

bookshelf-validation v0.0.4

Weekly downloads
3
License
MIT
Repository
github
Last release
8 years ago

bookshelf-validation

Build Status

A simple & flexible model validation plugin for bookshelf

How to use

You can install it from npm package.

$ npm install bookshelf-validation

And then plug it into bookshelf instance.

const knex = require('knex')({
  client: 'sqlite3',
  connection: { filename: ':memory:' }
});
const Bookshelf = require('bookshelf')(knex);

Bookshelf.plugin(require('bookshelf-validation'));

Now you are ready to use bookshelf-validation.

const validator = require('validator');

let User = Bookshelf.Model.extend({
  tableName: 'user',

  rules: {
    email: {
      required: true,
      validator: validator.isEmail
    },
    name: {
      required: true,
      validator: _.isString
    },
    age: { validator: _.isNumber },
    profileImage: { validator: validator.isURL },
    gender: { validator: _.contains.bind(null, ['male', 'female']) },
  },

  hasTimestamps: ['createdAt', 'updatedAt']
});

bookshelf-validation simply provides two model validation properties required and validator. The default value of required field is false unless you explicitly specify it. validator is just a function returns true / false, so it's highly customizable. I prefer to use it with validator library which has lots of built-in functions.