/** * @file * Attaches behaviors for the Clientside Validation jQuery module. */ (function ($, Drupal, once, drupalSettings) { 'use strict'; if (typeof drupalSettings.cvJqueryValidateOptions === 'undefined') { drupalSettings.cvJqueryValidateOptions = {}; } if (drupalSettings.clientside_validation_jquery.force_validate_on_blur) { drupalSettings.cvJqueryValidateOptions.onfocusout = function (element) { // "eager" validation this.element(element); }; } // Add messages with translations from backend. $.extend($.validator.messages, drupalSettings.clientside_validation_jquery.messages); // Overwrite default URL validation method, accepting public/private urlscheme. var _urlValidation = $.validator.methods.url; $.validator.methods.url = function(value, element) { return _urlValidation.call(this, value, element) || /^(public|private):\/\//.test(value); } /** * Attaches jQuery validate behavior to forms. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches the outline behavior to the right context. */ Drupal.behaviors.cvJqueryValidate = { attach: function (context) { if (typeof Drupal.Ajax !== 'undefined') { // Update Drupal.Ajax.prototype.beforeSend only once. if (typeof Drupal.Ajax.prototype.beforeSubmitCVOriginal === 'undefined') { var validateAll = 2; try { validateAll = drupalSettings.clientside_validation_jquery.validate_all_ajax_forms; } catch(e) { // Do nothing if we do not have settings or value in settings. } Drupal.Ajax.prototype.beforeSubmitCVOriginal = Drupal.Ajax.prototype.beforeSubmit; Drupal.Ajax.prototype.beforeSubmit = function (form_values, element_settings, options) { if (typeof this.$form !== 'undefined' && (validateAll === 1 || $(this.element).hasClass('cv-validate-before-ajax')) && $(this.element).attr("formnovalidate") == undefined) { $(this.$form).removeClass('ajax-submit-prevented'); // Handle for the HTML5 validation if enabled. var forceHtml5Validation = drupalSettings.clientside_validation_jquery.force_html5_validation; var formId = $(this.$form).attr('id'); if (forceHtml5Validation && formId) { if (!document.getElementById(formId).reportValidity()) { this.ajaxing = false; $(this.$form).addClass('ajax-submit-prevented'); return false; } } $(this.$form).validate(); if (!($(this.$form).valid())) { this.ajaxing = false; $(this.$form).addClass('ajax-submit-prevented'); return false; } } return this.beforeSubmitCVOriginal.apply(this, arguments); }; } } // Allow all modules to update the validate options. // Example of how to do this is shown below. $(document).trigger('cv-jquery-validate-options-update', drupalSettings.cvJqueryValidateOptions); // Process for all the forms on the page everytime, // we already use once so we should be good. once('cvJqueryValidate', 'body form').forEach(function(element) { $(element).validate(drupalSettings.cvJqueryValidateOptions); }); } }; })(jQuery, Drupal, once, drupalSettings);