Validate two fields so they do not match

Hey all,

I have two form fields (select dropdowns) that are ‘startlocation’ and
‘endlocation’. These two cannot be equal to each other on save and I am
wondering how to put validation into the model for this. Is is possible
to
do it in the model, or do I need to do this in the controller?

Thanks in advance!

Ryan

Ryan P. wrote:

Hey all,

I have two form fields (select dropdowns) that are ‘startlocation’ and
‘endlocation’. These two cannot be equal to each other on save and I am
wondering how to put validation into the model for this. Is is possible
to
do it in the model, or do I need to do this in the controller?

Thanks in advance!

Ryan

You can do it by overriding the validate method on the model e.g.

def validate
errors.add(‘startlocation’, ‘must be different to endlocation’) if
startlocation == endlocation
end

which will get called on every save. You can also override
validate_on_create and validate_on_update to get finer grained control.

Matt