Variables in regexp

bcardarella edited this page Jun 14, 2011 · 3 revisions

If you use variables in validation regexp like this one:

validates :username, :format => {:with => /^#{USERNAME_REGEXP}$/ }

then you will get JS error like this in firebug:

invalid quantifier

or this in Chrome:

Uncaught SyntaxError: Invalid regular expression: /^(?-mix:[A-Za-z0-9\_][A-Za-z0-9\-\_\.]+)$/: Invalid group

To avoid this, use #source method of Regexp class on included variable:

validates :username, :format => {:with => /^#{USERNAME_REGEXP.source}$/ }