Validation
JSON schema validation can be enabled by setting the jsonSchema property of a model class. The validation is ran each time a Model instance is created.
You rarely need to call $validate method explicitly, but you can do it when needed. If validation fails a ValidationError will be thrown. Since we use Promises, this usually means that a promise will be rejected with an instance of ValidationError.
See the recipe book for instructions if you want to use some other validation library.
Examples
All these will trigger the validation:
Person.fromJson({ firstName: 'jennifer', lastName: 'Lawrence' });
await Person.query().insert({ firstName: 'jennifer', lastName: 'Lawrence' });
await Person.query()
.update({ firstName: 'jennifer', lastName: 'Lawrence' })
.where('id', 10);
// Patch operation ignores the `required` property of the schema
// and only validates the given properties. This allows a subset
// of model's properties to be updated.
await Person.query()
.patch({ age: 24 })
.where('age', '<', 24);
await Person.query().insertGraph({
firstName: 'Jennifer',
pets: [
{
name: 'Fluffy'
}
]
});
await Person.query().upsertGraph({
id: 1,
pets: [
{
name: 'Fluffy II'
}
]
});Validation errors provide detailed error message:
try {
await Person.query().insert({ firstName: 'jennifer' });
} catch (err) {
console.log(err instanceof objection.ValidationError); // --> true
console.log(err.data); // --> {lastName: [{message: 'required property missing', ...}]}
}Error parameters returned by ValidationError could be used to provide custom error messages:
try {
await Person.query().insert({ firstName: 'jennifer' });
} catch (err) {
let lastNameErrors = err.data.lastName;
for (let i = 0; i < lastNameErrors.length; ++i) {
let lastNameError = lastNameErrors[i];
if (lastNameError.keyword === 'required') {
console.log('This field is required!');
} else if (lastNameError.keyword === 'minLength') {
console.log('Must be longer than ' + lastNameError.params.limit);
} else {
console.log(lastNameError.message); // Fallback to default error message
}
}
}Write-only properties
insertGraph() and upsertGraph() validate their models once the references and keys of the graph are resolved, after the models are created. A property that a setter consumes when the model is created, e.g. a password that a setter turns into a hash, is gone by then, and fails a required rule or skips its other rules. Keep such properties on the model and transform them in the $beforeInsert and $beforeUpdate hooks, which run after the validation in all queries:
class User extends Model {
static jsonSchema = {
type: 'object',
required: ['password'],
properties: {
password: { type: 'string', minLength: 8 }
},
};
async $beforeInsert(context) {
await super.$beforeInsert(context);
this.passwordHash = await hash(this.password);
delete this.password;
}
}