Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Created July 30, 2012 15:45
Show Gist options
  • Save choonkeat/3207929 to your computer and use it in GitHub Desktop.
Save choonkeat/3207929 to your computer and use it in GitHub Desktop.
rails active_model validator for singapore nric & car plate; courtesy www.tinkerbox.com.sg
class SingaporeLicensePlateValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "is not valid") unless valid_format?(value)
end
def valid_format?(license_plate)
prefix, numbers, suffix = license_plate.to_s.upcase.gsub(/\W+/, '').scan(/^\s*([A-Z]{1,3})(\d{1,4})(.+)$/).flatten
license_plate = ('%3s' % prefix.to_s) + ('%4d' % numbers.to_i) + suffix.to_s
zero = ('A'.ord-1).chr
numbers = []
license_plate.each_char {|char| numbers.push((num = char.ord - zero.ord) > 0 ? num : char)}
numbers = numbers.zip([3, 14, 2, 12, 2, 11, 1]).collect {|(a,b)| a.to_i * b.to_i }
remainder = numbers.sum % 19
'AYUSPLJGDBZXTRMKHEC'[remainder] == license_plate[-1]
end
end
# class Entity < ActiveRecord::Base
# validates :name, presence: true, singapore_nric: true
# end
class SingaporeNricValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "is not valid") unless valid_format?(value)
end
def valid_format?(nric)
nric = '%9s' % nric.to_s.upcase.gsub(/\W+/, '')
numbers = []
nric[1..7].to_s.each_char {|c| numbers.push(c.to_i) }
total = numbers.zip([2, 7, 6, 5, 4, 3, 2]).collect {|(a,b)| a.to_i * b.to_i }.sum
total += 4 if ['T', 'G'].include?(nric[0])
remainder = total % 11
result = (['S', 'T'].include?(nric[0]) ? 'JZIHGFEDCBA' : 'XWUTRQPNMLK')[remainder]
result == nric[-1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment