Home > Net >  How to trim whitespaces from inside of string with min_length and max_length validation?
How to trim whitespaces from inside of string with min_length and max_length validation?

Time:11-30

How to trim whitespace from inside of string with min_length and max_length validation?

name = serializers.CharField(min_length=18, max_length=18, trim_whitespace=True, allow_blank=True, allow_null=True, required=False)

test_string_that_should_be_invalid = "1111111111111111 1"

test_string_valid = "111111111111111111"

CodePudding user response:

The trim whitespace keyword argument doesn't run any extra validators. All it does is trim the whitespace at the end of a string using .strip() when saving the value to the database.

def to_internal_value(self, data):
    # We're lenient with allowing basic numerics to be coerced into strings,
    # but other types should fail. Eg. unclear if booleans should represent as `true` or `True`,
    # and composites such as lists are likely user error.
    if isinstance(data, bool) or not isinstance(data, (str, int, float,)):
        self.fail('invalid')
    value = str(data)
    return value.strip() if self.trim_whitespace else value

It sounds like you want to make sure that there are no spaces anywhere in the string. To do so you would need to write a custom field-level validator. Something like:

if ' ' in value:
    raise serializers.ValidationError('Value cannot contain spaces')
  • Related