Module: TextCaptcha::Validation::ClassMethods

Defined in:
lib/text_captcha/validation.rb

Instance Method Summary collapse

Instance Method Details

#validates_captcha(options = {}) ⇒ Object

Validate if answer for a captcha question is correct. If there’s no valid user, an error will be attached to :challenge_answer attribute.

class Comment < ActiveRecord::Base
  validates_captcha
end

By default the {:on => :create} options will be used. You can provide any other option you want.

class Comment < ActiveRecord::Base
  validates_captcha :if => :new_record?
end

@comment = Comment.new

@comment.challenge
#=> The color of a red T-shirt is?

@comment.challenge_answer = "red"
@comment.valid?
#=> true

Note that you can answer the question without worrying about uppercase/lowercase. All strings are normalized before the comparison. So “ReD”, “RED” or “red” will pass the validation.

You can use TextCaptcha with a non-ActiveRecord class. You just need to include the TextCaptcha::Validation module.

class Comment
  include ActiveModel::Validations
  include TextCaptcha::Validation

  validates_captcha
end

@comment = Comment.new
@comment.valid?
#=> false

@comment.errors[:challenge_answer]
#=> ["is not a valid answer"]


57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/text_captcha/validation.rb', line 57

def validates_captcha(options = {})
  attr_accessor :challenge_answer
  attr_writer :challenge_id

  # Only add default options if class descends from ActiveRecord.
  # Otherwise, validations won't run because regular classes don't
  # have save new record status.
  if self.ancestors.include?(::ActiveRecord::Base)
    options.reverse_merge!(on: :create)
  end

  validate :check_challenge_answer, options
end