diff --git a/app/models/voucher.rb b/app/models/voucher.rb index e963c2ab92..6d24830534 100644 --- a/app/models/voucher.rb +++ b/app/models/voucher.rb @@ -1,6 +1,8 @@ # frozen_string_literal: false class Voucher < ApplicationRecord + INVALID_CODE_REGEX = /(\r|\n)/ + acts_as_paranoid belongs_to :enterprise, optional: false @@ -12,7 +14,8 @@ class Voucher < ApplicationRecord before_validation :strip_code - validates :code, length: { maximum: STRING_COLUMN_LIMIT }, + validates :code, format: { without: INVALID_CODE_REGEX }, + length: { maximum: STRING_COLUMN_LIMIT }, presence: true, uniqueness: { scope: :enterprise_id } validates :amount, presence: true, numericality: { greater_than: 0 } diff --git a/spec/models/voucher_spec.rb b/spec/models/voucher_spec.rb index f965904ab1..7ccd223acd 100644 --- a/spec/models/voucher_spec.rb +++ b/spec/models/voucher_spec.rb @@ -27,6 +27,16 @@ describe Voucher do it { is_expected.to validate_uniqueness_of(:code).scoped_to(:enterprise_id) } it { is_expected.to validate_presence_of(:amount) } it { is_expected.to validate_numericality_of(:amount).is_greater_than(0) } + it { is_expected.to allow_value("somethingvalid").for(:code) } + + it "is invalid if the code contains certain forbidden characters e.g. new lines" do + voucher = subject + ["\n", "\r"].each do |forbidden_code_character| + voucher.code = "somethingvalid#{forbidden_code_character}somethingvalid" + expect(voucher).not_to be_valid + expect(voucher.errors[:code]).to eq(["is invalid"]) + end + end end describe '#compute_amount' do