Last active
December 12, 2015 09:49
-
-
Save deric/4754519 to your computer and use it in GitHub Desktop.
Validace rodného čísla v Ruby on Rails 3
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
# encoding: utf-8 | |
require 'date' | |
# Validation of Czech (Slovak) birth number | |
class BirthNumberValidator < ActiveModel::EachValidator | |
attr_reader :record, :attribute, :value | |
RC_FORMAT = Regexp.compile /^\s*(\d\d)(\d\d)(\d\d)[ -\/]*(\d\d\d)(\d?)\s*$/ | |
def validate_each(record, attribute, value) | |
@record, @attribute, @value = record, attribute, value | |
add_error unless valid? | |
end | |
def valid? | |
# "be liberal in what you receive" | |
m = value.match RC_FORMAT | |
if m == nil || m.size != 6 | |
return false | |
end | |
year, month, day, ext, c = m[1], m[2], m[3], m[4], m[5] | |
# do roku 1954 pridelovana devitimistna RC nelze overit | |
if c.empty? | |
return year.to_i < 54 | |
end | |
#zbytek po deleni 11 | |
#nemuzeme prevest na integer, protoze bychom prisli o nuly v cislech! | |
mod = "#{year}#{month}#{day}#{ext}".to_i % 11 | |
mod = 0 if mod == 10 | |
if mod != c.to_i | |
return false | |
end | |
#kontrola roku | |
year = year.to_i | |
month = month.to_i | |
day = day.to_i | |
year += year < 54 ? 2000 : 1900 | |
#k mesici muze byt pripocteno 20, 50, 70 | |
if month > 70 && year > 2003 | |
month -= 70 | |
elsif month > 50 | |
month -= 50 | |
elsif month > 20 && year > 2003 | |
month -= 20 | |
end | |
if Date.valid_date?(year, month, day) | |
return true | |
end | |
false | |
end | |
def add_error | |
if message = options[:message] | |
record.errors[attribute] << message | |
else | |
record.errors.add(attribute, :invalid) | |
end | |
end | |
end | |
#usage: | |
class Person < ActiveRecord::Base | |
# @see +BirthNumberValidator+ | |
validates :birth_number, :allow_blank => true, birth_number: true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment