Sha256: 92ad76298d334240a1df391707fe97ecc234bab07ecb62c66815715f33f51237

Contents?: true

Size: 1.49 KB

Versions: 3

Compression:

Stored size: 1.49 KB

Contents

class LinkValidator < ActiveModel::Validator
  def validate(record)
    record.changes.each do |field_name, (_, new_value)|
      if govspeak_fields(record).include?(field_name.to_sym)
        messages = errors(new_value)
        record.errors[field_name] << messages if messages
      end
    end
  end

  def errors(string)
    link_regex = %r{
      \[.*?\]           # link text in literal square brackets
      \(                # literal opening parenthesis
         (\S*?)           # containing URL
         (\s+"[^"]+")?    # and optional space followed by title text in quotes
      \)                # literal close paren
      (\{:rel=["']external["']\})?  # optional :rel=external in literal curly brackets.
    }x

    errors = Set.new

    string.scan(link_regex) do |match|

      if match[0] !~ %r{^(?:https?://|mailto:|/)}
        errors << 'Internal links must start with a forward slash eg [link text](/link-destination). External links must start with http://, https://, or mailto: eg [external link text](https://www.google.co.uk).'
      end
      if match[1]
        errors << %q-Don't include hover text in links. Delete the text in quotation marks eg "This appears when you hover over the link."-
      end
      if match[2]
        errors << 'Delete {:rel="external"} in links.'
      end

    end
    errors.to_a
  end

  protected

  def govspeak_fields(record)
    if record.class.const_defined?(:GOVSPEAK_FIELDS)
      record.class.const_get(:GOVSPEAK_FIELDS)
    else
      []
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
govuk_content_models-13.0.0 app/validators/link_validator.rb
govuk_content_models-12.4.0 app/validators/link_validator.rb
govuk_content_models-12.3.0 app/validators/link_validator.rb