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?
Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.
Custom validators take the value from the FormControl , where every input acts as a FormControl . So let's create a form along with a validator function. Create a new file called customvalidator. validator.
If you place your custom validators in app/validators
they will be automatically loaded without needing to alter your config/application.rb
file.
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.
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