Skip to content

Commit

Permalink
Add uuid validator
Browse files Browse the repository at this point in the history
Validates the uuid format. Uses basic regex, so doesn't:
1) Check if there is a matching resource
2) Check the the format matches the uuid standard precisely.
  • Loading branch information
James Glover committed Jun 10, 2022
1 parent fb3511f commit ea797ab
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
17 changes: 17 additions & 0 deletions app/validators/uuid_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

# UuidValidator
# Validates that the supplied value is a valid uuid
# by regular expression. This is a little more permissive
# than strictly governed by the UUID format, but we're more
# likely to see technically 'valid' uuids, which just don't
# map to a resource, so lets keep things simple.
class UuidValidator < ActiveModel::EachValidator
UUID = /\A[0-f]{8}-([0-f]{4}-){3}[0-f]{12}\z/.freeze

def validate_each(record, attribute, value)
return if UUID.match?(value)

record.errors.add(attribute, :uuid)
end
end
2 changes: 2 additions & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ en:
group_id:
duplicated_in_tag_set: must only appear once within a set
errors:
messages:
uuid: is not a valid uuid
attributes:
cost_code:
blank: must be present
Expand Down
39 changes: 39 additions & 0 deletions spec/validators/uuid_validator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe UuidValidator do
describe '#validate_each' do
let(:record_class) { Ont::Request }
let(:record) { record_class.new }
let(:attribute) { :external_study_id }

before do
described_class.new(attributes: [attribute]).validate_each(record, attribute, value)
end

context 'with a nil value' do
let(:value) { nil }

it 'adds an error to the record' do
expect(record.errors.full_messages).to include('External study is not a valid uuid')
end
end

context 'with a non-uuid' do
let(:value) { 'not-a-uuid' }

it 'adds an error to the record' do
expect(record.errors.full_messages).to include('External study is not a valid uuid')
end
end

context 'with a uuid' do
let(:value) { generate(:uuid) }

it 'adds an error to the record' do
expect(record.errors.full_messages).to be_empty
end
end
end
end

0 comments on commit ea797ab

Please sign in to comment.