验证子域的格式 [英] Validate format of subdomain

查看:27
本文介绍了验证子域的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确验证子域格式?

How can I properly validate a subdomain format?

这是我所拥有的:

  validates :subdomain, uniqueness: true, case_sensitive: false
  validates :subdomain, format: { with: /\A[A-Za-z0-9-]+\z/, message: "not a valid subdomain" }
  validates :subdomain, exclusion: { in: %w(support blog billing help api www host admin en ru pl ua us), message: "%{value} is reserved." }
  validates :subdomain, length: { maximum: 20 }
  before_validation :downcase_subdomain
  protected
    def downcase_subdomain
      self.subdomain.downcase! if attribute_present?("subdomain")
    end  

问题:

是否有像电子邮件一样的标准 REGEX 子域验证?子域使用的最佳正则表达式是什么?

Is there a standard REGEX subdomain validation like there is for email? What is the best REGEX for subdomain to use?

validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_blank: true

推荐答案

RFC 1035 定义了子域语法如下:

RFC 1035 defines subdomain syntax like so:

<subdomain> ::= <label> | <subdomain> "." <label>

<label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]

<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>

<let-dig-hyp> ::= <let-dig> | "-"

<let-dig> ::= <letter> | <digit>

<letter> ::= any one of the 52 alphabetic characters A through Z in
upper case and a through z in lower case

<digit> ::= any one of the ten digits 0 through 9

还有一个仁慈的人类可读的描述.

And a merciful human readable description.

[标签] 必须以字母开头,以字母或数字结尾,并且只有字母、数字和连字符作为内部字符.还有一些长度的限制.标签不得超过 63 个字符.

[Labels] must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen. There are also some restrictions on the length. Labels must be 63 characters or less.

我们可以使用正则表达式和长度限制单独完成大部分工作.

We can do most of this with a regex, and the length restriction separately.

validates :subdomain, format: {
  with: %r{\A[a-z](?:[a-z0-9-]*[a-z0-9])?\z}i, message: "not a valid subdomain"
}, length: { in: 1..63 }

将正则表达式分解成几部分来解释它.

Pulling that regex into pieces to explain it.

%r{
  \A
  [a-z]                       # must start with a letter
  (?:
    [a-z0-9-]*                # might contain alpha-numerics or a dash
    [a-z0-9]                  # must end with a letter or digit
  )?                          # that's all optional
 \z
}ix

我们可能想使用更简单的 /\A[az][a-z0-9-]*[a-z0-9]?\z/i 但这允许 foo-.

We might be tempted to use the simpler /\A[a-z][a-z0-9-]*[a-z0-9]?\z/i but this allows foo-.

另见子域的正则表达式.

这篇关于验证子域的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆