Skip to content

Instantly share code, notes, and snippets.

@kristenhazard
Created April 30, 2012 18:56
Show Gist options
  • Save kristenhazard/2561288 to your computer and use it in GitHub Desktop.
Save kristenhazard/2561288 to your computer and use it in GitHub Desktop.
Rails custom validation using answer_before_type_cast
class Answer < ActiveRecord::Base
validate :check_answer_validity
def check_answer_validity
raw_answer = self.answer_before_type_cast
answer_type = Question.find($question_id).answer_type
# first test the answer against the corresponding regex
case answer_type
when "# Attended", "# of Occurrences"
# regex allows "#" as valid match
show_error = /\A\d+\z/ === raw_answer ? false : true
when "0=No, 1=Yes"
# regex allows "0" or "1" as valid matches
show_error = /\A(0|1)\z/ === raw_answer ? false : true
when "Percent"
# regex allows "#", "#.#", "#.", or ".#" as valid matches
show_error = /\A(\d+([.]|)(\d+|)|(\d+|)([.]|)\d+)\z/ === raw_answer ? false : true
end
# then construct and show the error based on the answer test
if show_error
error = "^'#{raw_answer}' is an invalid entry for "
case answer_type
when "# Attended"
error += "'# Attended', you must enter a whole number, decimals are not allowed."
when "# of Occurrences"
error += "'# of Occurrences', you must enter a whole number, decimals are not allowed."
when "0=No, 1=Yes"
error += "'0=No, 1=Yes', you must enter only 0 for No or 1 for Yes."
when "Percent"
error += "'Percent', you must enter a whole number or decimal without the percent sign."
end
self.errors[:base] << error
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment