Ysh*_*rov 0 ruby regex subdomain ruby-on-rails
如何正确验证子域格式?
这是我所拥有的:
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
Run Code Online (Sandbox Code Playgroud)
题:
是否有像电子邮件一样的标准 REGEX 子域验证?子域使用的最佳正则表达式是什么?
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_blank: true
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
Run Code Online (Sandbox Code Playgroud)
和一个仁慈的人类可读的描述。
[标签] 必须以字母开头,以字母或数字结尾,并且只有字母、数字和连字符作为内部字符。长度也有一些限制。标签不得超过 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 }
Run Code Online (Sandbox Code Playgroud)
将该正则表达式分成几部分来解释它。
%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
Run Code Online (Sandbox Code Playgroud)
我们可能会想使用更简单的,/\A[a-z][a-z0-9-]*[a-z0-9]?\z/i但这允许foo-.
另请参阅子域的正则表达式。