如何使用 min_length 和 max_length 驗證從字串內部修剪空格?
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"
uj5u.com熱心網友回復:
修剪空白關鍵字引數不運行任何額外的驗證器。它所做的只是在.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
聽起來您想確保字串中的任何地方都沒有空格。為此,您需要撰寫自定義欄位級驗證器。就像是:
if ' ' in value:
raise serializers.ValidationError('Value cannot contain spaces')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370665.html
上一篇:計算分頁內的記錄,django
