views:

208

answers:

2

I want the sign up form on my site to have a field that takes the sum of a math equation and use rails validation to validate it. Whats the best way to do it?

i.e

What is 6 + 9 ? [ 8 ]

Error Message : You have entered the wrong number

A: 

This article on custom validations in rails is pretty good.

Jason Punyon
+1  A: 

Override the validate method in your model class. Remember that the model object you create for the new action is a different instance than the one created for the create action, so you'll need to save the random seed or the math expression somewhere in your form so that you can recreate it during validation.

Then, something along the lines of:

def validate
  unless math_equation_answered?
    errors.add("math_answer", "is incorrect")
  end
end

The implementation of math_equation_answered? is up to you, and math_answer should be changed to whatever model field you use for the user's answer.

Steve Madsen
I will try that and see if it works thank you Steve
IBarnes