Skip to content
This repository has been archived by the owner on Aug 18, 2021. It is now read-only.

Commit

Permalink
Add Front end validation to the required fields based on Drupal Example
Browse files Browse the repository at this point in the history
  • Loading branch information
Todd Dembrey committed Feb 8, 2018
1 parent 9832bb2 commit 2fd77fa
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
52 changes: 49 additions & 3 deletions opentech/apply/funds/static/address_form.js
Original file line number Diff line number Diff line change
@@ -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({
Expand Down
3 changes: 2 additions & 1 deletion opentech/apply/funds/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ class AddressWidget(NestedMultiWidget):

class Media:
js = (
'jquery.addressfield.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.addressfield.js',
# 'jquery.addressfield.min.js',
'address_form.js',
)

Expand Down

0 comments on commit 2fd77fa

Please sign in to comment.