Created
April 30, 2012 18:56
-
-
Save kristenhazard/2561288 to your computer and use it in GitHub Desktop.
Rails custom validation using answer_before_type_cast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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