python - Django 模型中域名的正则表达式匹配

标签 python regex django model

我有一张 table ,它看起来像:

class Tld(models.Model):
    domainNm = models.CharField(validators=[ RegexValidator('^[0-9]^[a-z]','yourdomain.com only','Invalid Entry')], max_length=40)
    dtCreated = models.DateField()

对于 domainNm - 我想验证任何看起来像这样的条目:

  • domain.com
  • 1domain.com
  • domain1.com

它必须遵循这种方式:<domainname>.[com|biz|net]等等,并且是字母数字。

我如何在 Django 模型的模型级别执行此操作?

谢谢

最佳答案

如果您想验证 HTTP URL,请忘记正则表达式并使用 builtin validator .

如果您只想要没有任何协议(protocol)的域,请尝试:

def full_domain_validator(hostname):
    """
    Fully validates a domain name as compilant with the standard rules:
        - Composed of series of labels concatenated with dots, as are all domain names.
        - Each label must be between 1 and 63 characters long.
        - The entire hostname (including the delimiting dots) has a maximum of 255 characters.
        - Only characters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9'.
        - Labels can't start or end with a hyphen.
    """
    HOSTNAME_LABEL_PATTERN = re.compile("(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE)
    if not hostname:
        return
    if len(hostname) > 255:
        raise ValidationError(_("The domain name cannot be composed of more than 255 characters."))
    if hostname[-1:] == ".":
        hostname = hostname[:-1]  # strip exactly one dot from the right, if present
    for label in hostname.split("."):
        if len(label) > 63:
            raise ValidationError(
                _("The label '%(label)s' is too long (maximum is 63 characters).") % {'label': label})
        if not HOSTNAME_LABEL_PATTERN.match(label):
            raise ValidationError(_("Unallowed characters in label '%(label)s'.") % {'label': label})

用法:

from django.core.validators import URLValidator

field = models.CharField(_('host name'), max_length=255, validators=[URLValidator])

field = models.CharField(_('host name'), max_length=255, validators=[full_domain_validator])

关于python - Django 模型中域名的正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821400/

相关文章:

python - 在 Python 中删除数字(正则表达式)

Django:为网站配置多个域?

html - 我的 CSS 文件未在 Django 中加载,但 Bootstrap 文件加载正常

javascript - NoReverseMatch 与 Django url

python - 将 string.format() 应用于 Pandas DataFrame 中的行

python - 简单的向下条形图(Python 3)

python - reshape ,重新组合行与列

python - 当值超出范围时,在二维数组中显示错误的轴

ios - 允许下划线和破折号的 swift ios 字母数字正则表达式

Javascript Regex - 匹配比表达式短的字符串?