Wes*_*ter 3 regex ruby-on-rails-4
我很难通过这个十六进制RGB验证来通过测试:
validates_format_of :primary_color, with: /#?([A-F0-9]{6}|[A-F0-9]{3})/i
Run Code Online (Sandbox Code Playgroud)
我正在测试以下值:
除"123ADG"外,所有测试均有效.它似乎通过了验证(意味着HEX值无效且应该失败,但它会通过).
我也试过这种正则表达式的变种,但无济于事:
validates_format_of :primary_color, with: /#?([A-F0-9]{3}){1,2}/i
Run Code Online (Sandbox Code Playgroud)
有什么建议?
您可以使用 Ruby\h字符类:
/\A#(?:\h{3}){1,2}\z/
其分解如下:
A# should starts with #
(
?: non-capturing group
\h a hexdigit character ([0-9a-fA-F])
{3} three times
)
{1,2} repeat either once or twice
Run Code Online (Sandbox Code Playgroud)
因此\h不需要/i修饰符,因此也需要小写\z