Sha256: 1d2f16c34345ce95b123b96d6444e532b1c50f467a01e0f77e6157b244fd1d0a

Contents?: true

Size: 1.43 KB

Versions: 6

Compression:

Stored size: 1.43 KB

Contents

# encoding: UTF-8

class LinkValidator < ActiveModel::Validator
  def validate(record)
    record.class::GOVSPEAK_FIELDS.each do |govspeak_field_name|
      govspeak_field_value = record.read_attribute(govspeak_field_name)
      next if govspeak_field_value.blank?

      messages = errors(govspeak_field_value)
      record.errors[govspeak_field_name] << messages if messages
    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.gsub(/(“|”)+/, '"').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
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
govuk_content_models-28.2.0 app/validators/link_validator.rb
govuk_content_models-28.1.0 app/validators/link_validator.rb
govuk_content_models-28.0.1 app/validators/link_validator.rb
govuk_content_models-28.0.0 app/validators/link_validator.rb
govuk_content_models-27.2.0 app/validators/link_validator.rb
govuk_content_models-27.1.0 app/validators/link_validator.rb