-
Notifications
You must be signed in to change notification settings - Fork 642
Description
At the moment a ValidationError only returns the name of the field which doesn't validate and a "default" message not very suitable for front-end. No other info about the validation context are exposed by the error class.
My proposal is to extend ValidationError changing the behavior and content of the data attribute with a more useful payload. This payload should include the validation keyword and params (returned by Ajv validation error in default implementation).
Something like:
model/AjvValidatior.js
function parseValidationError(errors) {
const errorHash = {};
let index = 0;
for (let i = 0; i < errors.length; ++i) {
// ...
// Here we pass a more useful payload for each key.
// Before was: errorHash[key] = error.message;
errorHash[key] = {
message: error.message,
keyword: error.keyword,
params: error.params
}
}
return new ValidationError(errorHash);
}
This is necessary to avoid nasty regex matches on front-end in order to individuate the scope of the validation error and to provide custom error messages without pains, e.g.:
MyModel
.query()
.patchAndFetchById(id, values)
.catch(function(err) {
if (err instanceof objection.ValidationError) {
Object.keys(err.data).forEach(function(key) {
let keyErr = err.data[key];
if (keyErr.keyword === 'minLength')
console.error("The field " + key + " is too short: must be at least " + keyErr.params.limit + " chars long!");
}
});
}
});
I could work on a PR for this.
For sure, it could break something so maybe a major release is required in order to include it mainstream.