module TextCaptcha::Validation::ClassMethods
Public Instance Methods
validates_captcha(options = {})
click to toggle source
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"]
# 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