Class: VinValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/vindicate/vin_validator.rb

Constant Summary collapse

VALID_CHARS =
/[A-HJ-NPR-Z0-9]{17}/i

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/vindicate/vin_validator.rb', line 4

def validate_each(record, attribute, value)
  return if value.blank?
  unless value.respond_to?(:length)
    record.errors.add(attribute, :invalid, message: 'is invalid')
    return
  end
  if value.length < 17
    record.errors.add(attribute, :invalid, message: 'is too short')
    return
  end
  if value.length > 17
    record.errors.add(attribute, :invalid, message: 'is too long')
    return
  end
  unless value =~ VALID_CHARS
    record.errors.add(attribute, :invalid, message: 'contains invalid characters')
    return
  end
  record.errors.add(attribute, :invalid, message: 'is invalid') unless valid?(value)
end