95

I've seen docs/websites show that custom validators should go in a /lib or /lib/validators directory of a project. I've found (by reading an answer to another post) that they only seem to work in config/initializers. Does anyone know, or have a pointer to official documentation that shows where custom validators should live?

JJD
  • 44,755
  • 49
  • 183
  • 309
Daniel D
  • 3,477
  • 4
  • 32
  • 40
  • How about [changing the accepted answer flag](http://stackoverflow.com/questions/5263239/where-should-rails-3-custom-validators-be-stored/6610270#comment16660135_6610270)? – JJD Oct 17 '13 at 08:07

4 Answers4

222

If you place your custom validators in app/validators they will be automatically loaded without needing to alter your config/application.rb file.

gbc
  • 7,887
  • 5
  • 32
  • 30
  • I don't know if there's some gem/config you need to add for this, but under rails 3.2.8 this doesn't work. Specifically, simply dropping your validator into app/validators/???.rb doesn't work. – Doug Aug 28 '12 at 06:22
  • 17
    Doug try to name the validator file same way the validator class is named but underscored: MyCoolValidator goes to app/validators/my_cool_validator.rb – equivalent8 Sep 11 '12 at 08:50
  • 14
    @Doug you need to restart your server. The autoload paths are expanded on initialization so new subfolders will not get picked up until you do that. – Timo Oct 08 '12 at 23:36
  • I like to also monkeypatch ActiveModel::Validations::HelperMethods to add a helper for my new validation (e.g. validates_address for AddressValidator). When I include both the monkeypatch and the Validator in app/validators/address_validator.rb only the AddressValidator object is loaded, not the monkeypatch. Are you guys experiencing the same behavior? – jshkol Dec 18 '12 at 23:58
  • 1
    `spring stop` was necessary for me in Rails 5.2, otherwise it wasn't picked up. – Jack Kinsella Nov 01 '18 at 11:57
15

If you add this to your /config/application.rb file:

config.autoload_paths += %W["#{config.root}/lib/validators/"]

Then Rails will automatically load your validators on start up (just like /config/initializers/), but you keep the clean structure of having your validators in one nice, well named spot.

Andrei
  • 9,162
  • 7
  • 68
  • 103
gunit888
  • 551
  • 6
  • 12
  • 9
    Good idea but your code needs some cleanup: `config.autoload_paths += %W(#{config.root}/lib/validators/)` – aNoble May 26 '11 at 20:46
6

lib/validators seems by far the cleanest. However you may need to load them in before your models, so probably from an initializer.

Jakub Hampl
  • 36,560
  • 8
  • 70
  • 101
4

Here's the official docs about custom validations. AFAIK its a good practice to keep them in the relevant models.

RameshVel
  • 60,384
  • 28
  • 166
  • 207
Shreyas
  • 8,447
  • 7
  • 40
  • 55