DRY validates_format_of?

In a model I have following validates_format_of. Is there an easy way to DRY this up? It seems to be rather repetitive.

  validates_format_of :expiration_date, :with => /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/   validates_format_of :activation_date, :with => /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/   validates_format_of :some_other_date, :with => /^[0-9]{4}[-][0-9]{2}[-][0-9]{2}$/ ....


Hi Jens,

validates_format_of takes a regular expression as its argument:

• with - The regular expression used to validate the format with (note: must be supplied!)

… so you just assign the regular expression to a variable

date_format = /[1]{4}[-][0-9]{2}[-][0-9]{2}$/

… and use it in your validates_format_of calls as follows:

validates_format_of :expiration_date, :with => date_format validates_format_of :activation_date, :with => date_format validates_format_of :some_other_date, :with => date_format

Note that class of the regexp:

~ $ irb

date_format = /[2]{4}[-][0-9]{2}[-][0-9]{2}$/

=> /[3]{4}[-][0-9]{2}[-][0-9]{2}$/


=> Regexp


=> Regexp


~ $

DRY is the future :slight_smile:


  1. 0-9 ↩︎

  2. 0-9 ↩︎

  3. 0-9 ↩︎

  4. 0-9 ↩︎

Sigh! ... so easy!

Thanks Peter for your time

I wrote a series of custom validations that in addition to defining a number of common character patterns as named validations, it also allowed multiple fields per validation


It made a huge difference in DRYness and the amount of code needed for validations.