Where should I put custom validators in Rails 5?

I am trying to add custom email validators for my application; However, where should I place a custom validator? (I really don't want to put this validation class in the model) Is there a cli generator for the validator?

http://guides.rubyonrails.org/active_record_validations.html

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

class Person < ApplicationRecord
  validates :email, presence: true, email: true
end

What is the location / convention path for a custom validator?

+4
source share
2 answers

I put them in /app/validators/email_validator.rband the validator will be loaded automatically.

, , , . , , .

  <div class="field">
    <%= f.label :email %>
    <%= f.text_field :email, required: true %>
  </div>

:

  <div class="field">
    <%= f.label :email %>
    <%= f.email_field :email, required: true %>
  </div>
+11

. , , :

> ActiveSupport::Dependencies.autoload_paths

, /application.rb, :

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

Source: https://habr.com/ru/post/1669834/


All Articles