如何使用 min_length 和 max_length 验证从字符串内部 trim 空格?
How to trim whitespaces from inside of string with min_length and max_length validation?
如何使用 min_length 和 max_length 验证从字符串内部 trim 空格?
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"
trim 空白关键字参数没有 运行 任何额外的验证器。它所做的只是 trim 在将值保存到数据库时使用 .strip()
字符串末尾的空格。
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
听起来您想确保字符串中的任何地方都没有空格。为此,您需要编写 custom field-level validator。类似于:
if ' ' in value:
raise serializers.ValidationError('Value cannot contain spaces')
如何使用 min_length 和 max_length 验证从字符串内部 trim 空格?
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"
trim 空白关键字参数没有 运行 任何额外的验证器。它所做的只是 trim 在将值保存到数据库时使用 .strip()
字符串末尾的空格。
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
听起来您想确保字符串中的任何地方都没有空格。为此,您需要编写 custom field-level validator。类似于:
if ' ' in value:
raise serializers.ValidationError('Value cannot contain spaces')