Reputation: 190
According to the Loopback 4 documentation, you can add a custom error message on the validation of a model like so:
jsonSchema: {
maxLength: 30,
minLength: 10,
errorMessage:
'name must be at least 10 characters and maximum 30 characters',
},
I would like to generate a custom error message in this way, but I am only getting the default error messages for the given validation. This is my code:
jsonSchema: {
maxLength: 13,
errorMessage: "Primary phone number is required and should be formatted like (XXX) XXX-XXXX",
pattern: "[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}",
},
})
When I give it a string like "123 456-789" I get this:
{ "error": { "statusCode": 422, "name": "UnprocessableEntityError", "message": "The request body is invalid. See error object
details
property for more info.", "code": "VALIDATION_FAILED", "details": [ { "path": "/primary_phone", "code": "pattern", "message": "should match pattern \"[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}\"", "info": { "pattern": "[(][0-9]{3}[)] [0-9]{3}-[0-9]{4}" } } ] } }
I've tried a wide variety of placement for errorMessage and fiddled around with spelling, but nothing changes the error I get. Is there something else I need to do to get these custom error messages to show up?
Upvotes: 0
Views: 410
Reputation: 196
Loopback member Hage Yaapa informed me that this is a case of bad documentation. The missing piece is this:
this.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS).to({
validation: {
ajvKeywords: true,
ajvErrors: true
}
});
This must be added to your application/context in order to enable the extra functionality for custom errors.
Upvotes: 1