Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save oksana-c/981a6d544a76677efadeaa2224558969 to your computer and use it in GitHub Desktop.
Save oksana-c/981a6d544a76677efadeaa2224558969 to your computer and use it in GitHub Desktop.
D8 - HTML5 checkbox and radio buttons form validation.js
/**
* Adds client side validation for radio buttons and checkboxes.
*/
(function($) {
Drupal.behaviors.mymodule_form_validate = {
attach: function(context, settings) {
// If parent fieldset for the radio buttons or checkbox group
// has attribute "required" add "required attribute to all child
// radio button and checkbox elements.
$('.fieldgroup').each(function() {
if($(this).is('[required]')) {
$(this).find('.form-radio').attr('required', 'required');
$(this).find('div.form-checkboxes').addClass('required');
}
});
var validateCheckboxes = function () {
$(".required.form-checkboxes").each(function() {
var checkboxes = $(this).find('.form-type-checkbox');
var inputs = checkboxes.find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
first.checkValidity();
});
};
$('#edit-submit').on('click', function() {
validateCheckboxes();
});
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment