Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails validate RGB hex

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:

  • sdf (should fail)
  • 123ADG (should fail)
  • 336699 (should pass)
  • FFF (should pass)

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?

like image 847
Wes Foster Avatar asked Jun 05 '15 20:06

Wes Foster


2 Answers

Use anchors with your pattern ...

/\A#?(?:[A-F0-9]{3}){1,2}\z/i
like image 76
hwnd Avatar answered Sep 20 '22 19:09

hwnd


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

like image 29
spirito_libero Avatar answered Sep 20 '22 19:09

spirito_libero