子域的有效格式

问题描述 投票:0回答:1

如何正确验证子域格式?

这是我所拥有的:

  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子域验证?子域名使用的最佳REGEX是什么?

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

ruby-on-rails regex ruby subdomain
1个回答
2
投票

RFC 1035定义子域语法,如下所示:

<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

以及仁慈的人类可读描述。

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

我们可以使用正则表达式和长度限制来分别完成大部分操作。

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 }

将该正则表达式拉成碎片进行解释。

%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[a-z][a-z0-9-]*[a-z0-9]?\z/i,但这允许foo-

另请参见Regexp for subdomain

© www.soinside.com 2019 - 2024. All rights reserved.