Ruby on rails 验证子域的格式
如何正确验证子域格式 以下是我得到的:Ruby on rails 验证子域的格式,ruby-on-rails,regex,ruby,subdomain,Ruby On Rails,Regex,Ruby,Subdomain,如何正确验证子域格式 以下是我得到的: 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
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子域验证?子域使用的最佳正则表达式是什么
验证:email,格式:{with:URI::MailTo::email\u REGEXP},允许\u blank:true定义子域语法如下:
<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
把正则表达式分成几部分来解释它
%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-
另请参见。域和子域可以是数字、文本或混合字符,但不能是%、$、^等字符。为什么不使用URI.parse?@max如果实际域以结尾无效,子域如何有效?你能给我们举一个有效值和无效值的例子吗?我重新措辞了这个问题,以澄清我想要的是什么,非常好的解释,并特别感谢你最后对正则表达式的解释@不客气。我刚刚写了一些类似的东西,这让我意识到我有一个bug,我忘记了破折号。域验证经常出现,这促使我研究并了解如何添加子域/标签验证程序。
%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