marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

Disabling message_all in Validators

Open songofroland opened this issue 6 years ago • 1 comments

I need to implement dictionary of custom error messages per validator. E.g. client needs to know if value is too small or too large. It would be easy when only min or max parameter is present, but when both are message_all is returned by default. I need to override _call_ method like this in every validator to avoid using this message:

class Range(validate.Range):
    message_min = TOO_SMALL
    message_max = TOO_LARGE

    def __call__(self, value):

        if self.min is not None and (
            value < self.min if self.min_inclusive else value <= self.min
        ):
            message = self.message_min
            raise ValidationError(self._format_error(value, message))

        if self.max is not None and (
            value > self.max if self.max_inclusive else value >= self.max
        ):
            message = self.message_max
            raise ValidationError(self._format_error(value, message))

        return value

Is there any better approach or it's possible issue to be improved?

songofroland avatar Sep 11 '20 07:09 songofroland

I don't really see what the problem is and what we should modify in the core to allow easier customization.

Only Range and List are concerned, so you may override them once then inherit from your new class.

Closing this for now as unclear. Feel free to comment if you want this reconsidered.

lafrech avatar Apr 08 '21 19:04 lafrech