Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knex.js: incorporating validation rules in create, update, and delete queries

Is it possible to incorporate data validation rules for Create, Update, and Delete operations when using the Knex.js query builder library, even though Knex does not do this out of the box?

If yes, then:

  • is it a good idea or bad idea to stay inside Knex for this?
  • if it is an OK approach, is there a decent example of this someone can point to?
  • would you be better off and have less friction if you include Bookshelf.js?

Even Bookshelf does not come with a validation engine.

like image 429
mg1075 Avatar asked Sep 25 '22 14:09

mg1075


1 Answers

It would be better to use bookshelf since it provides events during the transaction. While bookshelf doesn't come with a built in validation engine, you can use Checkit. It is built by the same author of Knex and Bookshelf. By hooking into the saving event, you can effectively validate your model.

Here's a simple example:

var User = Bookshelf.Model.extend({
    tableName: 'users',
    initialize: function() {
        this.on('saving', this.validate, this);
    },
    validations: {
        email: ['required', 'validEmail'],
        username: ['required', 'alphaNumeric'],
        age: ['isNumeric']
    },
    validate: function(model, attrs, options) {
        return CheckIt(this.toJSON()).run(this.validations);
    }
});

Check out this issue thread on GH for more insight.

like image 96
Seth Avatar answered Oct 19 '22 22:10

Seth