【问题标题】:Validate format of subdomain验证子域的格式
【发布时间】:2020-02-17 20:27:34
【问题描述】:

如何正确验证子域格式?

这是我得到的:

  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 子域验证?子域使用的最佳正则表达式是什么?

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

【问题讨论】:

  • 域和子域可以是数字、文本或混合字符,但不能是%,$,^,&等字符...
  • 为什么不使用URI.parse()
  • @max 如果实际域以- 结尾无效,那么子域如何有效? namecheap.com/domains/registration/…
  • 你能给我们一个有效和无效值的例子吗?
  • 我重新表述了这个问题以明确我在寻找什么

标签: ruby-on-rails regex ruby subdomain


【解决方案1】:

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

【讨论】:

  • 精彩的解释,特别感谢最后的正则表达式解释!
  • @Yshmarov 不客气。我刚刚写了类似的东西,这让我意识到我有一个错误,我忘记了破折号。域验证经常出现,它提示我在 validates_hostname 上工作,并了解如何添加子域/标签验证器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 2014-07-28
相关资源
最近更新 更多