2023-02-08 14:21:39 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class FormTemplateYamlValidator < ActiveModel::Validator
|
2023-08-29 17:41:33 -04:00
|
|
|
RESERVED_KEYWORDS = %w[title body category category_id tags]
|
|
|
|
ALLOWED_TYPES = %w[checkbox dropdown input multi-select textarea upload]
|
|
|
|
|
2023-02-08 14:21:39 -05:00
|
|
|
def validate(record)
|
|
|
|
begin
|
|
|
|
yaml = Psych.safe_load(record.template)
|
2023-08-29 17:41:33 -04:00
|
|
|
check_missing_fields(record, yaml)
|
2023-03-01 14:07:13 -05:00
|
|
|
check_allowed_types(record, yaml)
|
2023-08-29 17:41:33 -04:00
|
|
|
check_ids(record, yaml)
|
2023-02-08 14:21:39 -05:00
|
|
|
rescue Psych::SyntaxError
|
|
|
|
record.errors.add(:template, I18n.t("form_templates.errors.invalid_yaml"))
|
|
|
|
end
|
|
|
|
end
|
2023-03-01 14:07:13 -05:00
|
|
|
|
|
|
|
def check_allowed_types(record, yaml)
|
|
|
|
yaml.each do |field|
|
2023-08-29 17:41:33 -04:00
|
|
|
if !ALLOWED_TYPES.include?(field["type"])
|
2023-03-01 14:07:13 -05:00
|
|
|
return(
|
|
|
|
record.errors.add(
|
|
|
|
:template,
|
|
|
|
I18n.t(
|
|
|
|
"form_templates.errors.invalid_type",
|
|
|
|
type: field["type"],
|
2023-08-29 17:41:33 -04:00
|
|
|
valid_types: ALLOWED_TYPES.join(", "),
|
2023-03-01 14:07:13 -05:00
|
|
|
),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-08-29 17:41:33 -04:00
|
|
|
def check_missing_fields(record, yaml)
|
2023-03-01 14:07:13 -05:00
|
|
|
yaml.each do |field|
|
|
|
|
if field["type"].blank?
|
2023-08-29 17:41:33 -04:00
|
|
|
return(record.errors.add(:template, I18n.t("form_templates.errors.missing_type")))
|
|
|
|
end
|
|
|
|
if field["id"].blank?
|
|
|
|
return(record.errors.add(:template, I18n.t("form_templates.errors.missing_id")))
|
2023-03-01 14:07:13 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2023-08-29 17:41:33 -04:00
|
|
|
|
|
|
|
def check_ids(record, yaml)
|
|
|
|
ids = []
|
|
|
|
yaml.each do |field|
|
|
|
|
next if field["id"].blank?
|
|
|
|
|
|
|
|
if RESERVED_KEYWORDS.include?(field["id"])
|
|
|
|
return(
|
|
|
|
record.errors.add(:template, I18n.t("form_templates.errors.reserved_id", id: field["id"]))
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
if ids.include?(field["id"])
|
|
|
|
return(record.errors.add(:template, I18n.t("form_templates.errors.duplicate_ids")))
|
|
|
|
end
|
|
|
|
|
|
|
|
ids << field["id"]
|
|
|
|
end
|
|
|
|
end
|
2023-02-08 14:21:39 -05:00
|
|
|
end
|