Django Mod中域名的Regex匹配

2024-05-03 00:58:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张桌子,看起来像:

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-我想验证任何类似的条目:

  • 在域名.com在
  • 1域名.com在
  • 域名1.com

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

如何在django模型的模型级别上执行此操作?在

谢谢


Tags: 模型comonlymodelmodelsclass域名charfield
2条回答

如果要验证httpurl,请忽略regex并使用builtin validator。在

如果只需要没有任何协议的域,请尝试:

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})

用法:

^{pr2}$

或者

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

回顾一下上面的说明:您只想匹配具有单个字母数字标签和最多4个字符的TLD的域,例如。”域名.com“或”其他域名信息“或”345xyz.pdq1“但不是”子域.domain.com“,”http://domain.com“,”www.domain.com网站或“345”xyz.abcde". 此正则表达式将执行以下操作:

^[a-z0-9]+\.[a-z0-9]{1,4}$

相关问题 更多 >