I'm working on a form using a model that isn't tied to a database or
ORM at all and using ActiveModel::Validations works like a charm. I'm
very pleased with it thus far.
However, I can't find an obvious way to validate a single field rather
than the whole model. Is there a simple way to do this?
I am not aware of such a feature but you could write your own
validation method in the model and invoke it like any other method
after the field is populated.
I tried to figure out how .valid? did it by tracing back through the
code and ultimate found a method being called:
_run_validate_callbacks
Unfortunately, I couldn't find the actual def anywhere because I'm
guessing something in ActiveSupport::Callbacks creates the method. I
didn't have a desire to go through all the metaprogramming, but after
some digging I found enough to write this method:
def validate_field(field)
field = field.to_sym
if self._validators[field]
self.errors.clear
self._validators[field].each { |v| v.validate self }
self.errors[field]
else
nil
end
end
The reason for this method is that I have a form that validates as you
fill it out via AJAX. One of the validation calls is pretty expensive
so I don't want it called every time I do something like check to see
if the passwords match.