Form level validation, where to do it

Form level validation involving enforcing a relation between two or
more form inputs that may not even be in the model:

I am building a form that will query a range of records between two
dates.

The form ask for a starting data and a ending date.

I want to validate that the user selected a starting data before or
equal to the ending date.

It seems that this validation should happen in the controller, rather
than in the model.

If it should happen in the model, what would be an example?

( a more complex, but maybe idea way would be to do the validation for
this in javascript in the client browser?)

Or if it makes since in the controller, how do I do validation in the
controller?

One option would be to put it in the controller. You can simply check
the
dates and create an instance variable containing an error message. That
isn’t very DRY though. Want to do it somewhere else? Then you’re
duplicating
the code.

Another option is to create a dummy model that does not inherit from
ActiveRecord, then include the validations there. If you add the right
methods, you can interact with it just like a normal AR model. Something
like this should get you started:

class MySearchClass

include ActiveModel::Validations

validates :start_date
validates :end_date

def save
return false unless valid?
# the dates were valid, go ahead and query the records
return true
end

end

On 28 February 2011 17:36, [email protected]
[email protected] wrote:

It seems that this validation should happen in the controller, rather
than in the model.

If it should happen in the model, what would be an example?

( a more complex, but maybe idea way would be to do the validation for
this in javascript in the client browser?)

Or if it makes since in the controller, how do I do validation in the
controller?

I would not call this ‘validation’ as that term is normally kept for
checking data being saved in the db. What you are doing here is just
checking that the parameters to the controller action are ok before
accepting the action. In that case I would say it is fine in the
controller to check the dates before allowing the action.

The javascript method is probably arguably even better as it avoids
the round trip to the server. I would probably not bother with the
additional complication however, it is not a regular occurrence
(presumably) and even if you validate in javascript you will still
have to check in the controller in case the user has javascript
disabled.

Colin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs