3

Let's say that I have an input field with a value, and I want to validate it (on the server side) to make sure, for instance, that the field has at least 5 characters.

The problem is that it is not something that I want to save in the database, or build a model. I just want to check that the value validates.

In PHP with Laravel, validation is quite easy:

$validator = Validator::make($data, [
    'email' => ['required', 'email'],
    'message' => ['required']]);

if ($validator->fails()) { // Handle it... }

Is there anything similar in Rails, without need of ActiveRecord, or ActiveModel? Not every data sent from a form makes sense as a Model.

3
  • Why not use javascript validation in the form and use form object robots.thoughtbot.com/activemodel-form-objects. It will help you reuse the form and its logic at other places if necessary.
    – coderhs
    Aug 23, 2014 at 9:51
  • Client-side validation can be manipulated by the user, is not reliable Aug 23, 2014 at 10:07
  • About that link you added, it requires that the information you are posting can be defined as a resource (which is basically the same as defining a model). I am looking for validation without that much fuzz. Simple and direct, like in the PHP example. Aug 23, 2014 at 10:09

2 Answers 2

14

You can use ActiveModel::Validations like this

class MyClass
  include ActiveModel::Validations

  validates :email, presence: true
  validates :message, presence: true
end

It will act as a normal model and you will be able to do my_object.valid? and my_object.errors.

8
  • 3
    As I said in the question, is there a way to make it without Models? Not every set of data sent through a form is meant to be a model. Aug 23, 2014 at 9:40
  • 1
    This is not a model, this is a class. This is the ruby way. If you have a complex things to do, you will do it a class. Ruby is a really oriented object language.
    – Dougui
    Aug 23, 2014 at 9:46
  • 1
    So there isnt any way or Validation Helper to make validations in a simple direct way? Aug 23, 2014 at 9:48
  • The only other way to do it I see is to do it manually but I don't see a reason to not use a class.
    – Dougui
    Aug 23, 2014 at 9:50
  • 1
    That would depend maybe on the nature of the application. In any case, I want to know if it is doable. Aug 23, 2014 at 10:41
5

Rails validations live in ActiveModel so doing it without ActiveModel seems kind of counter-productive. Now, if you can loosen that requirement a bit, it is definitely possible.

What I read you asking for, and as I read the PHP code doing, is a validator-object that can be configured on the fly.

We can for example build a validator class dynamically and use instance of that class to run our validations. I have opted for an API that looks similar to the PHP one here:

class DataValidator
  def self.make(data, validations)
    Class.new do
      include ActiveModel::Validations

      attr_reader(*validations.keys)

      validations.each do |attribute, attribute_validations|
        validates attribute, attribute_validations
      end

      def self.model_name
        ActiveModel::Name.new(self, nil, "DataValidator::Validator")
      end

      def initialize(data)
        data.each do |key, value|
          self.instance_variable_set("@#{key.to_sym}", value)
        end
      end
    end.new(data)
  end
end

Using DataValidator.make we can now build instances of classes with the specific validations that we need. For example in a controller:

validator = DataValidator.make(
  params,
  {
    :email => {:presence => true},
    :name => {:presence => true}
  }
)
if validator.valid?
  # Success
else
  # Error
end
4
  • Good point, I just want to ask, where would I basically add this class? Is it better to add this under controller or model?
    – mpalencia
    Jun 17, 2016 at 8:40
  • I guess that's a matter of preference more than anything. It's not a controller, so that's probably not the right place. It's not really a business object either, so app/models might not be the best place. lib is an existing alternative, or you could create app/validators or some such.
    – Jakob S
    Jun 17, 2016 at 11:52
  • @JakobS - thank you for your answer + cool metaprogramming. What is the significance of using Class.new do.....end.New()? What is that doing, and why are you doing it that way? Can't see do everything that the above code is doing simply by ommitting Class.new do....end and pasting everything directly in the DataValidator class?
    – BenKoshy
    Jan 16, 2020 at 2:33
  • So Class.new {} returns a new class and the subsequent .new(data) returns an instance of that class, which means that DataValidator.make returns an instance that you can call valid? on. You cannot copy/paste the contents of the block into a new class, because the contents depend on 2 arguments, although I'd love to be proven wrong :) It's a dynamic and more complex way of doing what's hardcoded in Douguis answer, which actually does what the original PHP code did; namely build a validator object.
    – Jakob S
    Jan 17, 2020 at 7:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.