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:
Even Bookshelf does not come with a validation engine.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With