Created
April 15, 2016 09:31
-
-
Save ebrett/8abb19ea5b1881de0ba240c7f202fb33 to your computer and use it in GitHub Desktop.
This file contains 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 FullNameValidator < ActiveModel::Validator | |
def validate(person) | |
error_string = '' | |
error_string += blank_name?(person.title, person.first_name, person.last_name) | |
error_string += first_name_too_long(person.first_name) | |
error_string += first_name_too_short(person.first_name) | |
error_string += last_name_too_long(person.last_name) | |
return true if error_string == '' | |
person.errors.add :full_name, I18n.t(error_string) | |
end | |
private | |
def blank_name?(title, first, last) | |
err = '' | |
err += 'title_' if title.blank? | |
err += 'first_' if first.blank? | |
err += 'last_' if last.blank? | |
error?(err, 'blank') | |
end | |
def first_name_too_long(first) | |
err = '' | |
err += '_first_too_long' if first.length > 50 | |
err += '_first_too_short' if first.length < 2 | |
error?(err, 'length') | |
end | |
def first_name_too_short(first) | |
err = '' | |
err += '_first_too_short' if first.length < 2 | |
error?(err, 'length') | |
end | |
def last_name_too_long(last) | |
err = '' | |
err = '_last_too_long' if last.length > 100 | |
error?(err, 'length') | |
end | |
def error?(error_str, respond_str) | |
(error_str == '') ? error_str : error_str += respond_str | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment