在模型外使用 Django 的 RegexValidator
Using Django's RegexValidator outside of models
我使用 Django 的内置库定义了一个正则表达式验证器。我用它来验证我模型上的字段。像这样:
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])
但是,我如何在我的领域之外使用它?就像我想使用验证器验证字符串 'Hello'
一样,前提是验证器存储在常规变量而不是模型中。文档看起来很混乱。
谢谢。
很简单:验证器是可调用的,因此您只需使用要验证的值调用它,如果该值未验证,它将引发 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.']
>>>
我使用 Django 的内置库定义了一个正则表达式验证器。我用它来验证我模型上的字段。像这样:
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])
但是,我如何在我的领域之外使用它?就像我想使用验证器验证字符串 'Hello'
一样,前提是验证器存储在常规变量而不是模型中。文档看起来很混乱。
谢谢。
很简单:验证器是可调用的,因此您只需使用要验证的值调用它,如果该值未验证,它将引发 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.']
>>>