本文整理汇总了Python中django.core.validators.RegexValidator方法的典型用法代码示例。如果您正苦于以下问题:Python validators.RegexValidator方法的具体用法?Python validators.RegexValidator怎么用?Python validators.RegexValidator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.validators
的用法示例。
在下文中一共展示了validators.RegexValidator方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def __init__(self, *args, **kwargs):
self.ocd_type = kwargs.pop("ocd_type")
if self.ocd_type != "jurisdiction":
kwargs["default"] = lambda: "ocd-{}/{}".format(self.ocd_type, uuid.uuid4())
# len('ocd-') + len(ocd_type) + len('/') + len(uuid)
# = 4 + len(ocd_type) + 1 + 36
# = len(ocd_type) + 41
kwargs["max_length"] = 41 + len(self.ocd_type)
regex = (
"^ocd-" + self.ocd_type + "/[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$"
)
else:
kwargs["max_length"] = 300
regex = common.JURISDICTION_ID_REGEX
kwargs["primary_key"] = True
# get pattern property if it exists, otherwise just return the object (hopefully a string)
msg = "ID must match " + getattr(regex, "pattern", regex)
kwargs["validators"] = [RegexValidator(regex=regex, message=msg, flags=re.U)]
super(OCDIDField, self).__init__(*args, **kwargs)
示例2: _set_regex
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def _set_regex(self, regex):
if isinstance(regex, six.string_types):
regex = re.compile(regex, re.UNICODE)
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
self.validators.remove(self._regex_validator)
self._regex_validator = validators.RegexValidator(regex=regex)
self.validators.append(self._regex_validator)
示例3: get_fields
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def get_fields(self):
fields = super().get_fields()
name_field = fields.get('name')
for validator in name_field.validators:
if isinstance(validator, RegexValidator):
if validator.regex.pattern == r'^[-a-zA-Z0-9_]+$':
validator.regex = re.compile(r'^[-\w]+\Z')
return fields
示例4: _set_regex
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def _set_regex(self, regex):
if isinstance(regex, str):
regex = re.compile(regex)
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
self.validators.remove(self._regex_validator)
self._regex_validator = validators.RegexValidator(regex=regex)
self.validators.append(self._regex_validator)
示例5: validate_color
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def validate_color(color):
"""
Check the color is either #123 or #123456
"""
validators.RegexValidator(
r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$',
'{} is not a valid color, it must be either #123 or #123456'.format(color),
)(color)
示例6: validate_email_address_content
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def validate_email_address_content(email_address):
"""Make sure we only create valid emails."""
regex_validator = RegexValidator(regex=EmailValidator.user_regex)
reserved_valdator = ReservedNameValidator()
regex_validator(email_address.email)
reserved_valdator(email_address.email)
示例7: __init__
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
initial = kwargs.get('initial', {})
initial['right_picture'] = ''
kwargs['initial'] = initial
super(_Activity, self).__init__(*args, **kwargs)
self.fields['right_picture'].help_text = _('Use a valid imgur URL such as http://i.imgur.com/6oHYT4B.png')
self.fields['right_picture'].label = _('Picture')
self.fields['right_picture'].validators.append(RegexValidator(
regex=settings.IMGUR_REGEXP,
message='Invalid Imgur URL',
code='invalid_url',
))
示例8: alphanumeric_validator
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def alphanumeric_validator():
return RegexValidator(r'^[a-zA-Z0-9-_ ]+$',
'Only numbers, letters, underscores, dashes and spaces are allowed.')
示例9: zipped_file_validator
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def zipped_file_validator():
return RegexValidator(r'.*\.(ZIP|zip)$',
'Only compressed archive (.zip) files are allowed.')
示例10: test_all_errors_get_reported
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def test_all_errors_get_reported(self):
class UserForm(forms.Form):
full_name = forms.CharField(
max_length=50,
validators=[
validators.validate_integer,
validators.validate_email,
]
)
string = forms.CharField(
max_length=50,
validators=[
validators.RegexValidator(
regex='^[a-zA-Z]*$',
message="Letters only.",
)
]
)
ignore_case_string = forms.CharField(
max_length=50,
validators=[
validators.RegexValidator(
regex='^[a-z]*$',
message="Letters only.",
flags=re.IGNORECASE,
)
]
)
form = UserForm({
'full_name': 'not int nor mail',
'string': '2 is not correct',
'ignore_case_string': "IgnORE Case strIng",
})
with self.assertRaises(ValidationError) as e:
form.fields['full_name'].clean('not int nor mail')
self.assertEqual(2, len(e.exception.messages))
self.assertFalse(form.is_valid())
self.assertEqual(form.errors['string'], ["Letters only."])
self.assertEqual(form.errors['string'], ["Letters only."])
示例11: _set_regex
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def _set_regex(self, regex):
if isinstance(regex, six.string_types):
regex = re.compile(regex)
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
self.validators.remove(self._regex_validator)
self._regex_validator = validators.RegexValidator(regex=regex)
self.validators.append(self._regex_validator)
示例12: test_serialize_class_based_validators
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def test_serialize_class_based_validators(self):
"""
Ticket #22943: Test serialization of class-based validators, including
compiled regexes.
"""
validator = RegexValidator(message="hello")
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.RegexValidator(message='hello')")
self.serialize_round_trip(validator)
# Test with a compiled regex.
validator = RegexValidator(regex=re.compile(r'^\w+$', re.U))
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$', 32))")
self.serialize_round_trip(validator)
# Test a string regex with flag
validator = RegexValidator(r'^[0-9]+$', flags=re.U)
string = MigrationWriter.serialize(validator)[0]
if PY36:
self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag(32))")
else:
self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=32)")
self.serialize_round_trip(validator)
# Test message and code
validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')")
self.serialize_round_trip(validator)
# Test with a subclass.
validator = EmailValidator(message="hello")
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.EmailValidator(message='hello')")
self.serialize_round_trip(validator)
validator = deconstructible(path="migrations.test_writer.EmailValidator")(EmailValidator)(message="hello")
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "migrations.test_writer.EmailValidator(message='hello')")
validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
with self.assertRaisesRegex(ImportError, "No module named '?custom'?"):
MigrationWriter.serialize(validator)
validator = deconstructible(path="django.core.validators.EmailValidator2")(EmailValidator)(message="hello")
with self.assertRaisesMessage(ValueError, "Could not find object EmailValidator2 in django.core.validators."):
MigrationWriter.serialize(validator)
示例13: test_serialize_class_based_validators
# 需要导入模块: from django.core import validators [as 别名]
# 或者: from django.core.validators import RegexValidator [as 别名]
def test_serialize_class_based_validators(self):
"""
Ticket #22943: Test serialization of class-based validators, including
compiled regexes.
"""
validator = RegexValidator(message="hello")
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.RegexValidator(message='hello')")
self.serialize_round_trip(validator)
# Test with a compiled regex.
validator = RegexValidator(regex=re.compile(r'^\w+$'))
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))")
self.serialize_round_trip(validator)
# Test a string regex with flag
validator = RegexValidator(r'^[0-9]+$', flags=re.S)
string = MigrationWriter.serialize(validator)[0]
if PY36:
self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag(16))")
else:
self.assertEqual(string, "django.core.validators.RegexValidator('^[0-9]+$', flags=16)")
self.serialize_round_trip(validator)
# Test message and code
validator = RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')")
self.serialize_round_trip(validator)
# Test with a subclass.
validator = EmailValidator(message="hello")
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "django.core.validators.EmailValidator(message='hello')")
self.serialize_round_trip(validator)
validator = deconstructible(path="migrations.test_writer.EmailValidator")(EmailValidator)(message="hello")
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(string, "migrations.test_writer.EmailValidator(message='hello')")
validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
with self.assertRaisesMessage(ImportError, "No module named 'custom'"):
MigrationWriter.serialize(validator)
validator = deconstructible(path="django.core.validators.EmailValidator2")(EmailValidator)(message="hello")
with self.assertRaisesMessage(ValueError, "Could not find object EmailValidator2 in django.core.validators."):
MigrationWriter.serialize(validator)