I'm having a hard time getting this hex RGB validation to pass tests:
validates_format_of :primary_color, with: /#?([A-F0-9]{6}|[A-F0-9]{3})/i
I'm testing against the following values:
All of the tests work, except for "123ADG". It seems to pass the validation (meaning the HEX value is invalid and should fail, but instead it passes).
I've also tried this variation of regex, but to no avail:
validates_format_of :primary_color, with: /#?([A-F0-9]{3}){1,2}/i
Any suggestions?
Use anchors with your pattern ...
/\A#?(?:[A-F0-9]{3}){1,2}\z/i
You can use Ruby \h
character class:
/\A#(?:\h{3}){1,2}\z/
Which breaks down as follows:
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
Hence \h
does not require a /i
modifier and also hence lowercase \z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With