From 2fd77faacadeaeaaf60badd33f71f2cab9d4e3d4 Mon Sep 17 00:00:00 2001 From: Todd Dembrey <todd.dembrey@torchbox.com> Date: Wed, 31 Jan 2018 17:08:05 +0000 Subject: [PATCH] Add Front end validation to the required fields based on Drupal Example --- opentech/apply/funds/static/address_form.js | 52 +++++++++++++++++++-- opentech/apply/funds/widgets.py | 3 +- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/opentech/apply/funds/static/address_form.js b/opentech/apply/funds/static/address_form.js index d0c308f93..ab67198de 100644 --- a/opentech/apply/funds/static/address_form.js +++ b/opentech/apply/funds/static/address_form.js @@ -1,13 +1,59 @@ (function ($) { + // add the require attribute to the field configs + function addRequiredToKey(fields, findKey){ + $.each(fields, (index, value) => { + var fieldName = Object.keys(value)[0]; + var data = value[fieldName]; + if (fieldName===findKey) { + data.required = true; + } else if (Array.isArray(data)) { + // Handle nested fields + addRequiredToKey(data, findKey); + } + }); + } + + + // hook into the transform to update with the required attribute var oldTransform = $.fn.addressfield.transform; $.fn.addressfield.transform = function(data) { var mappedData = oldTransform.call(this, data); + $.each(mappedData, (key, value) => { + $.each(value.required, (index, field) => { + addRequiredToKey(mappedData[key].fields, field); + }); + }); return mappedData; }; - $('.form').bind('addressfield:after', function (e, data) { - debugger; - }); + function labelFor(field){ + return $('label[for="'+ $(field).attr('id') +'"]'); + } + + function makeFieldNotRequired(field){ + var $field = $(field); + $(this).prop('required', false); + var $label = labelFor($field); + $label.children('span').remove(); + } + + function makeFieldRequired(field){ + var $field = $(field); + $field.prop('required', true); + var $label = labelFor($field); + $label.append('<span class="form__required">*</span>'); + } + + // Hook into the validate process to update the required display + var oldValidate = $.fn.addressfield.validate; + $.fn.addressfield.validate = function(field, config) { + if (config.required) { + makeFieldRequired(this); + } else { + makeFieldNotRequired(this); + } + oldValidate.call(this, field, config); + }; $(document).ready(function formReady() { $('.form div.address').addressfield({ diff --git a/opentech/apply/funds/widgets.py b/opentech/apply/funds/widgets.py index 7bcf0eb42..09cf7e95e 100644 --- a/opentech/apply/funds/widgets.py +++ b/opentech/apply/funds/widgets.py @@ -60,7 +60,8 @@ class AddressWidget(NestedMultiWidget): class Media: js = ( - 'jquery.addressfield.min.js', + 'https://cdn.jsdelivr.net/npm/jquery.addressfield@1.1.0/dist/jquery.addressfield.js', + # 'jquery.addressfield.min.js', 'address_form.js', ) -- GitLab