diff --git a/lib/custom_wizard/validators/update.rb b/lib/custom_wizard/validators/update.rb index 0db83c01..9a586359 100644 --- a/lib/custom_wizard/validators/update.rb +++ b/lib/custom_wizard/validators/update.rb @@ -1,3 +1,5 @@ +require 'addressable/uri' + class ::CustomWizard::UpdateValidator attr_reader :updater @@ -37,7 +39,7 @@ class ::CustomWizard::UpdateValidator @updater.errors.add(field_id, I18n.t('wizard.field.too_long', label: label, max: max_length.to_i)) end - if is_url_type(field) && !check_if_url(value) + if is_url_type(field) && value.present? && !check_if_url(value) @updater.errors.add(field_id, I18n.t('wizard.field.not_url', label: label)) end @@ -110,9 +112,14 @@ class ::CustomWizard::UpdateValidator def is_url_type(field) ['url'].include? field.type end - - def check_if_url(value) - value =~ URI::regexp + + SCHEMES ||= %w(http https) + + def check_if_url(url) + parsed = Addressable::URI.parse(url) or return false + SCHEMES.include?(parsed.scheme) + rescue Addressable::URI::InvalidURIError + false end def standardise_boolean(value) diff --git a/spec/components/custom_wizard/update_validator_spec.rb b/spec/components/custom_wizard/update_validator_spec.rb index 996c1548..4c854dcd 100644 --- a/spec/components/custom_wizard/update_validator_spec.rb +++ b/spec/components/custom_wizard/update_validator_spec.rb @@ -10,11 +10,7 @@ describe CustomWizard::UpdateValidator do } before do - CustomWizard::Template.save( - JSON.parse(File.open( - "#{Rails.root}/plugins/discourse-custom-wizard/spec/fixtures/wizard.json" - ).read), - skip_jobs: true) + CustomWizard::Template.save(template, skip_jobs: true) @template = CustomWizard::Template.find('super_mega_fun_wizard') end @@ -114,4 +110,25 @@ describe CustomWizard::UpdateValidator do updater.errors.messages[:step_1_field_2].first ).to eq(I18n.t('wizard.field.required', label: 'Textarea')) end + + it 'validates url fields' do + updater = perform_validation('step_2', step_2_field_6: 'https://discourse.com') + expect( + updater.errors.messages[:step_2_field_6].first + ).to eq(nil) + end + + it 'does not validate url fields with non-url inputs' do + updater = perform_validation('step_2', step_2_field_6: 'discourse') + expect( + updater.errors.messages[:step_2_field_6].first + ).to eq(I18n.t('wizard.field.not_url', label: 'Url')) + end + + it 'validates empty url fields' do + updater = perform_validation('step_2', step_2_field_6: '') + expect( + updater.errors.messages[:step_2_field_6].first + ).to eq(nil) + end end \ No newline at end of file diff --git a/spec/fixtures/wizard.json b/spec/fixtures/wizard.json index ffad241c..9b91d768 100644 --- a/spec/fixtures/wizard.json +++ b/spec/fixtures/wizard.json @@ -81,6 +81,11 @@ "label": "Checkbox", "type": "checkbox" }, + { + "id": "step_2_field_6", + "label": "Url", + "type": "url" + }, { "id": "step_2_field_7", "label": "Upload",