When our object fails validation, we should generate the same human-readable error messages as we did before. To do this, we must process the errors stored at ajvValidate.errors, and use them to generate human-readable messages. Thus, create a new module at src/validators/errors/messages.js, and copy the following message generator:
function generateValidationErrorMessage(errors) {
const error = errors[0];
if (error.dataPath.indexOf('.profile') === 0) {
return 'The profile provided is invalid.';
}
if (error.keyword === 'required') {
return 'Payload must contain at least the email and password fields';
}
if (error.keyword === 'type') {
return 'The email and password fields must be of type string';
}
if (error.keyword === 'format') {
return 'The email field must be a valid email.';
}
return 'The object is invalid';
}
export default generateValidationErrorMessage;
The generateValidationErrorMessage function extracts the first error object from the ajvValidate.errors array, and use it to generate the appropriate error message. There's also a generic, default error message in case none of the conditionals apply.