當前位置: 首頁>>代碼示例>>Python>>正文


Python validators.RegexValidator方法代碼示例

本文整理匯總了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) 
開發者ID:opencivicdata,項目名稱:python-opencivicdata,代碼行數:22,代碼來源:base.py

示例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) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:10,代碼來源:fields.py

示例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 
開發者ID:KubeOperator,項目名稱:KubeOperator,代碼行數:10,代碼來源:project.py

示例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) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:10,代碼來源:fields.py

示例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) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:10,代碼來源:models.py

示例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) 
開發者ID:webkom,項目名稱:lego,代碼行數:10,代碼來源:validators.py

示例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',
        )) 
開發者ID:MagiCircles,項目名稱:SchoolIdolAPI,代碼行數:15,代碼來源:forms.py

示例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.') 
開發者ID:nasa-jpl-memex,項目名稱:memex-explorer,代碼行數:5,代碼來源:models.py

示例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.') 
開發者ID:nasa-jpl-memex,項目名稱:memex-explorer,代碼行數:5,代碼來源:models.py

示例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."]) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:43,代碼來源:test_validators.py

示例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) 
開發者ID:erigones,項目名稱:esdc-ce,代碼行數:10,代碼來源:fields.py

示例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) 
開發者ID:denisenkom,項目名稱:django-sqlserver,代碼行數:50,代碼來源:test_writer.py

示例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) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:50,代碼來源:test_writer.py


注:本文中的django.core.validators.RegexValidator方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。