|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'uri' |
| 4 | + |
| 5 | +# Validate whether text fields contain external links |
| 6 | +class ContainsExternalLinksValidator < ActiveModel::EachValidator |
| 7 | + def validate_each(record, attribute, value) |
| 8 | + uris = extract_uris(value) |
| 9 | + record.errors.add(attribute, 'cannot contain external links') if uris.length.positive? |
| 10 | + end |
| 11 | + |
| 12 | + private |
| 13 | + |
| 14 | + def extract_uris(value) |
| 15 | + URI.extract(value) |
| 16 | + end |
| 17 | +end |
| 18 | + |
| 19 | +# app/models/document_type.rb |
| 20 | +class DocumentType < ApplicationRecord |
| 21 | + has_paper_trail |
| 22 | + |
| 23 | + belongs_to :user, optional: true |
| 24 | + |
| 25 | + has_many :documents |
| 26 | + |
| 27 | + validates :name, length: { maximum: 50 } |
| 28 | + validates :name, presence: true |
| 29 | + validates :name, uniqueness: true |
| 30 | + validates :name, contains_external_links: true |
| 31 | + validates_format_of :name, with: /^[a-zA-Z\d ]*$/i, multiline: true, message: 'can only contain letters and numbers.' |
| 32 | + validates :description, presence: true |
| 33 | + validates :description, uniqueness: true |
| 34 | + validates :description, length: { maximum: 200 } |
| 35 | + validates :description, contains_external_links: true |
| 36 | + validates :status, inclusion: { in: %w[approved pending declined], allow_nil: false } |
| 37 | +end |
0 commit comments