在模型之外使用Django的RegexValidator

时间:2018-10-26 11:31:38

标签: django django-validation

我使用Django的内置库定义了一个正则表达式验证器。我用它来验证模型上的字段。像这样:

RewriteEngine On

# If /newweb is requested directly then redirect to remove it
RewriteCond %{REDIRECT_STATUS} ^$
RewriteRule ^newweb/?(.*) /$1 [R=302,L]

# Rewrite enverything to the /newweb subdirectory
RewriteRule !^newweb/ /newweb%{REQUEST_URI} [L]

但是,如何在我的领域之外使用它?就像可以说的,如果验证器存储在常规变量而不是模型中,我想使用验证器来验证字符串from django.core.validators import RegexValidator validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.') class MyModel(models.Model): label = models.CharField(max_length=40, validators=[validate_alphanumeric]) 。这些文档似乎很令人困惑。

谢谢。

1 个答案:

答案 0 :(得分:2)

十分简单:验证器是可调用的,因此您只需将其与要验证的值一起调用即可,如果该值未验证,它将引发ValidationError

>>> from django.core.validators import RegexValidator
>>> validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.')
>>> validate_alphanumeric("foo") # ok, nothing happens
>>> validate_alphanumeric("++") # raises a ValidationError
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/bruno/.virtualenvs/blook/local/lib/python2.7/site-packages/django/core/validators.py", line 61, in __call__
    raise ValidationError(self.message, code=self.code)
ValidationError: [u'Only alphanumeric characters are allowed.']
>>>