Skip to content

Commit

Permalink
Added a person ID validator that accepts DNI and NIE numbers and fixe…
Browse files Browse the repository at this point in the history
…d NIE validator
  • Loading branch information
javiertoledo committed Apr 17, 2013
1 parent 47764dc commit 270c10a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Or install it yourself as:
Just use any of the following validators.

# A person id
class Person < ActiveRecord::Base
class Spaniard < ActiveRecord::Base
validates :dni, :valid_nif => true
end

Expand All @@ -45,9 +45,14 @@ Just use any of the following validators.
validates :nie, :valid_nie => true
end

# Any person id
class Person < ActiveRecord::Base
validates :any_id, :valid_spanish_id => true
end

# Any kind of id is valid
class SpanishSubject < ActiveRecord::Base
validates :id, :valid_spanish_vat => true
validates :nif, :valid_spanish_vat => true
end

## Contributing
Expand Down
19 changes: 13 additions & 6 deletions lib/spanish_vat_validators.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,11 @@ def validate_cif(value)
end
end

# Validates NIE, in fact is a fake, a NIE is really a NIF with first number changed to capital 'X' letter, so we change the first X to a 0 and then try to
# pass the nif validator
# Validates NIE
# a NIE is really a NIF with first number changed to capital X, Y or Z letter
def validate_nie(value)
return false unless value.match(/[x][0-9]{7,8}[a-z]/i)
value[0] = '0'
value.slice(0) if value.size > 9
return false unless value.match(/[xyz][0-9]{7}[a-z]/i)
value[0] = {"X" => "0", "Y" => "1", "Z" => "2"}[value[0]]
validate_nif(value)
end
end
Expand All @@ -65,6 +64,14 @@ def validate_each(record, attribute, value)
end
end

# Validates any Spanish person number
class ValidSpanishIdValidator < ActiveModel::EachValidator
include SpanishVatValidatorsHelpers
def validate_each(record, attribute, value)
record.errors[attribute] = message unless validate_nif(value.clone) or validate_nie(value.clone)
end
end

# Validates NIF number only
class ValidNifValidator < ActiveModel::EachValidator
include SpanishVatValidatorsHelpers
Expand All @@ -85,7 +92,7 @@ def validate_each(record, attribute,value)
class ValidNieValidator < ActiveModel::EachValidator
include SpanishVatValidatorsHelpers
def validate_each(record, attribute,value)
record.errors[attribute] = message('nie') unless validate_cif(value.clone)
record.errors[attribute] = message('nie') unless validate_nie(value.clone)
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/spanish_vat_validators/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module SpanishVatValidators
VERSION = "0.0.1"
VERSION = "0.0.3"
end

0 comments on commit 270c10a

Please sign in to comment.