I'm trying to add a customized error message for a class field in Marshamallow's schema. The field representation looks like this:
phone_number = fields.String(validate=Length(max=20),
error_messages={'invalid': 'Phone number must be a string shorter than'
'20 letters.'})
I was expecting that after loading the request data to a schema, I would get the error "Phone number must be a string shorter than 20 letters.", however, I'm still receiving the default message "Longer than maximum length 20.". The code for loading the request data is:
try:
request_data = EditInvestorSchema().load(request.json)
except ValidationError as error:
return get_response(400, list(error.messages.values())[0])
Can anyone shed some light on what might be happening?
CodePudding user response:
If you define the message in the validator it should work. See here for the documentation of the validator.
phone_number = fields.String(
validate=Length(
max=20,
error='Phone number must be a string shorter than 20 letters.'
)
)