def METHOD_NAME(name_field, *, allow_root, hostname=True):
    pattern = (
        # https://github.com/PowerDNS/pdns/blob/4646277d05f293777a3d2423a3b188ccdf42c6bc/pdns/dnsname.cc#L419
        re.compile(r"^(([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)\.)+$")
        if hostname
        else
        # https://github.com/PowerDNS/pdns/blob/4646277d05f293777a3d2423a3b188ccdf42c6bc/pdns/dnsname.cc#L473
        # with the exception of [/@ :\\]
        re.compile(r"^(([A-Za-z0-9_*-]+)\.)+$")
    )
    class Mixin:
        def to_text(self, origin=None, relativize=True, **kw):
            name = getattr(self, name_field)
            if (
                not (allow_root and name == dns.name.root)
                and pattern.match(str(name)) is None
            ):
                raise ValueError(f"invalid {name_field}: {name}")
            return super().to_text(origin, relativize, **kw)
    return Mixin