[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/media/system/js/fields/ -> validate-es5.js (source)

   1  (function () {
   2    'use strict';
   3  
   4    function _defineProperties(target, props) {
   5      for (var i = 0; i < props.length; i++) {
   6        var descriptor = props[i];
   7        descriptor.enumerable = descriptor.enumerable || false;
   8        descriptor.configurable = true;
   9        if ("value" in descriptor) descriptor.writable = true;
  10        Object.defineProperty(target, descriptor.key, descriptor);
  11      }
  12    }
  13  
  14    function _createClass(Constructor, protoProps, staticProps) {
  15      if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  16      if (staticProps) _defineProperties(Constructor, staticProps);
  17      Object.defineProperty(Constructor, "prototype", {
  18        writable: false
  19      });
  20      return Constructor;
  21    }
  22  
  23    function _unsupportedIterableToArray(o, minLen) {
  24      if (!o) return;
  25      if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  26      var n = Object.prototype.toString.call(o).slice(8, -1);
  27      if (n === "Object" && o.constructor) n = o.constructor.name;
  28      if (n === "Map" || n === "Set") return Array.from(o);
  29      if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  30    }
  31  
  32    function _arrayLikeToArray(arr, len) {
  33      if (len == null || len > arr.length) len = arr.length;
  34  
  35      for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  36  
  37      return arr2;
  38    }
  39  
  40    function _createForOfIteratorHelperLoose(o, allowArrayLike) {
  41      var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  42      if (it) return (it = it.call(o)).next.bind(it);
  43  
  44      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  45        if (it) o = it;
  46        var i = 0;
  47        return function () {
  48          if (i >= o.length) return {
  49            done: true
  50          };
  51          return {
  52            done: false,
  53            value: o[i++]
  54          };
  55        };
  56      }
  57  
  58      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  59    }
  60  
  61    /** Highest positive signed 32-bit float value */
  62    var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
  63  
  64    /** Bootstring parameters */
  65  
  66    var base = 36;
  67    var tMin = 1;
  68    var tMax = 26;
  69    var skew = 38;
  70    var damp = 700;
  71    var initialBias = 72;
  72    var initialN = 128; // 0x80
  73  
  74    var delimiter = '-'; // '\x2D'
  75  
  76    /** Regular expressions */
  77  
  78    var regexPunycode = /^xn--/;
  79    var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
  80  
  81    var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
  82  
  83    /** Error messages */
  84  
  85    var errors = {
  86      'overflow': 'Overflow: input needs wider integers to process',
  87      'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  88      'invalid-input': 'Invalid input'
  89    };
  90    /** Convenience shortcuts */
  91  
  92    var baseMinusTMin = base - tMin;
  93    var floor = Math.floor;
  94    var stringFromCharCode = String.fromCharCode;
  95    /*--------------------------------------------------------------------------*/
  96  
  97    /**
  98     * A generic error utility function.
  99     * @private
 100     * @param {String} type The error type.
 101     * @returns {Error} Throws a `RangeError` with the applicable error message.
 102     */
 103  
 104    function error(type) {
 105      throw new RangeError(errors[type]);
 106    }
 107    /**
 108     * A generic `Array#map` utility function.
 109     * @private
 110     * @param {Array} array The array to iterate over.
 111     * @param {Function} callback The function that gets called for every array
 112     * item.
 113     * @returns {Array} A new array of values returned by the callback function.
 114     */
 115  
 116  
 117    function map(array, fn) {
 118      var result = [];
 119      var length = array.length;
 120  
 121      while (length--) {
 122        result[length] = fn(array[length]);
 123      }
 124  
 125      return result;
 126    }
 127    /**
 128     * A simple `Array#map`-like wrapper to work with domain name strings or email
 129     * addresses.
 130     * @private
 131     * @param {String} domain The domain name or email address.
 132     * @param {Function} callback The function that gets called for every
 133     * character.
 134     * @returns {Array} A new string of characters returned by the callback
 135     * function.
 136     */
 137  
 138  
 139    function mapDomain(string, fn) {
 140      var parts = string.split('@');
 141      var result = '';
 142  
 143      if (parts.length > 1) {
 144        // In email addresses, only the domain name should be punycoded. Leave
 145        // the local part (i.e. everything up to `@`) intact.
 146        result = parts[0] + '@';
 147        string = parts[1];
 148      } // Avoid `split(regex)` for IE8 compatibility. See #17.
 149  
 150  
 151      string = string.replace(regexSeparators, '\x2E');
 152      var labels = string.split('.');
 153      var encoded = map(labels, fn).join('.');
 154      return result + encoded;
 155    }
 156    /**
 157     * Creates an array containing the numeric code points of each Unicode
 158     * character in the string. While JavaScript uses UCS-2 internally,
 159     * this function will convert a pair of surrogate halves (each of which
 160     * UCS-2 exposes as separate characters) into a single code point,
 161     * matching UTF-16.
 162     * @see `punycode.ucs2.encode`
 163     * @see <https://mathiasbynens.be/notes/javascript-encoding>
 164     * @memberOf punycode.ucs2
 165     * @name decode
 166     * @param {String} string The Unicode input string (UCS-2).
 167     * @returns {Array} The new array of code points.
 168     */
 169  
 170  
 171    function ucs2decode(string) {
 172      var output = [];
 173      var counter = 0;
 174      var length = string.length;
 175  
 176      while (counter < length) {
 177        var value = string.charCodeAt(counter++);
 178  
 179        if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
 180          // It's a high surrogate, and there is a next character.
 181          var extra = string.charCodeAt(counter++);
 182  
 183          if ((extra & 0xFC00) == 0xDC00) {
 184            // Low surrogate.
 185            output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
 186          } else {
 187            // It's an unmatched surrogate; only append this code unit, in case the
 188            // next code unit is the high surrogate of a surrogate pair.
 189            output.push(value);
 190            counter--;
 191          }
 192        } else {
 193          output.push(value);
 194        }
 195      }
 196  
 197      return output;
 198    }
 199    /**
 200     * Creates a string based on an array of numeric code points.
 201     * @see `punycode.ucs2.decode`
 202     * @memberOf punycode.ucs2
 203     * @name encode
 204     * @param {Array} codePoints The array of numeric code points.
 205     * @returns {String} The new Unicode string (UCS-2).
 206     */
 207  
 208  
 209    var ucs2encode = function ucs2encode(array) {
 210      return String.fromCodePoint.apply(String, array);
 211    };
 212    /**
 213     * Converts a basic code point into a digit/integer.
 214     * @see `digitToBasic()`
 215     * @private
 216     * @param {Number} codePoint The basic numeric code point value.
 217     * @returns {Number} The numeric value of a basic code point (for use in
 218     * representing integers) in the range `0` to `base - 1`, or `base` if
 219     * the code point does not represent a value.
 220     */
 221  
 222  
 223    var basicToDigit = function basicToDigit(codePoint) {
 224      if (codePoint - 0x30 < 0x0A) {
 225        return codePoint - 0x16;
 226      }
 227  
 228      if (codePoint - 0x41 < 0x1A) {
 229        return codePoint - 0x41;
 230      }
 231  
 232      if (codePoint - 0x61 < 0x1A) {
 233        return codePoint - 0x61;
 234      }
 235  
 236      return base;
 237    };
 238    /**
 239     * Converts a digit/integer into a basic code point.
 240     * @see `basicToDigit()`
 241     * @private
 242     * @param {Number} digit The numeric value of a basic code point.
 243     * @returns {Number} The basic code point whose value (when used for
 244     * representing integers) is `digit`, which needs to be in the range
 245     * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 246     * used; else, the lowercase form is used. The behavior is undefined
 247     * if `flag` is non-zero and `digit` has no uppercase form.
 248     */
 249  
 250  
 251    var digitToBasic = function digitToBasic(digit, flag) {
 252      //  0..25 map to ASCII a..z or A..Z
 253      // 26..35 map to ASCII 0..9
 254      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
 255    };
 256    /**
 257     * Bias adaptation function as per section 3.4 of RFC 3492.
 258     * https://tools.ietf.org/html/rfc3492#section-3.4
 259     * @private
 260     */
 261  
 262  
 263    var adapt = function adapt(delta, numPoints, firstTime) {
 264      var k = 0;
 265      delta = firstTime ? floor(delta / damp) : delta >> 1;
 266      delta += floor(delta / numPoints);
 267  
 268      for (; delta > baseMinusTMin * tMax >> 1; k += base) {
 269        delta = floor(delta / baseMinusTMin);
 270      }
 271  
 272      return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
 273    };
 274    /**
 275     * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 276     * symbols.
 277     * @memberOf punycode
 278     * @param {String} input The Punycode string of ASCII-only symbols.
 279     * @returns {String} The resulting string of Unicode symbols.
 280     */
 281  
 282  
 283    var decode = function decode(input) {
 284      // Don't use UCS-2.
 285      var output = [];
 286      var inputLength = input.length;
 287      var i = 0;
 288      var n = initialN;
 289      var bias = initialBias; // Handle the basic code points: let `basic` be the number of input code
 290      // points before the last delimiter, or `0` if there is none, then copy
 291      // the first basic code points to the output.
 292  
 293      var basic = input.lastIndexOf(delimiter);
 294  
 295      if (basic < 0) {
 296        basic = 0;
 297      }
 298  
 299      for (var j = 0; j < basic; ++j) {
 300        // if it's not a basic code point
 301        if (input.charCodeAt(j) >= 0x80) {
 302          error('not-basic');
 303        }
 304  
 305        output.push(input.charCodeAt(j));
 306      } // Main decoding loop: start just after the last delimiter if any basic code
 307      // points were copied; start at the beginning otherwise.
 308  
 309  
 310      for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) {
 311        // `index` is the index of the next character to be consumed.
 312        // Decode a generalized variable-length integer into `delta`,
 313        // which gets added to `i`. The overflow checking is easier
 314        // if we increase `i` as we go, then subtract off its starting
 315        // value at the end to obtain `delta`.
 316        var oldi = i;
 317  
 318        for (var w = 1, k = base;; k += base) {
 319          if (index >= inputLength) {
 320            error('invalid-input');
 321          }
 322  
 323          var digit = basicToDigit(input.charCodeAt(index++));
 324  
 325          if (digit >= base || digit > floor((maxInt - i) / w)) {
 326            error('overflow');
 327          }
 328  
 329          i += digit * w;
 330          var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
 331  
 332          if (digit < t) {
 333            break;
 334          }
 335  
 336          var baseMinusT = base - t;
 337  
 338          if (w > floor(maxInt / baseMinusT)) {
 339            error('overflow');
 340          }
 341  
 342          w *= baseMinusT;
 343        }
 344  
 345        var out = output.length + 1;
 346        bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`,
 347        // incrementing `n` each time, so we'll fix that now:
 348  
 349        if (floor(i / out) > maxInt - n) {
 350          error('overflow');
 351        }
 352  
 353        n += floor(i / out);
 354        i %= out; // Insert `n` at position `i` of the output.
 355  
 356        output.splice(i++, 0, n);
 357      }
 358  
 359      return String.fromCodePoint.apply(String, output);
 360    };
 361    /**
 362     * Converts a string of Unicode symbols (e.g. a domain name label) to a
 363     * Punycode string of ASCII-only symbols.
 364     * @memberOf punycode
 365     * @param {String} input The string of Unicode symbols.
 366     * @returns {String} The resulting Punycode string of ASCII-only symbols.
 367     */
 368  
 369  
 370    var encode = function encode(input) {
 371      var output = []; // Convert the input in UCS-2 to an array of Unicode code points.
 372  
 373      input = ucs2decode(input); // Cache the length.
 374  
 375      var inputLength = input.length; // Initialize the state.
 376  
 377      var n = initialN;
 378      var delta = 0;
 379      var bias = initialBias; // Handle the basic code points.
 380  
 381      for (var _iterator = _createForOfIteratorHelperLoose(input), _step; !(_step = _iterator()).done;) {
 382        var _currentValue2 = _step.value;
 383  
 384        if (_currentValue2 < 0x80) {
 385          output.push(stringFromCharCode(_currentValue2));
 386        }
 387      }
 388  
 389      var basicLength = output.length;
 390      var handledCPCount = basicLength; // `handledCPCount` is the number of code points that have been handled;
 391      // `basicLength` is the number of basic code points.
 392      // Finish the basic string with a delimiter unless it's empty.
 393  
 394      if (basicLength) {
 395        output.push(delimiter);
 396      } // Main encoding loop:
 397  
 398  
 399      while (handledCPCount < inputLength) {
 400        // All non-basic code points < n have been handled already. Find the next
 401        // larger one:
 402        var m = maxInt;
 403  
 404        for (var _iterator2 = _createForOfIteratorHelperLoose(input), _step2; !(_step2 = _iterator2()).done;) {
 405          var currentValue = _step2.value;
 406  
 407          if (currentValue >= n && currentValue < m) {
 408            m = currentValue;
 409          }
 410        } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
 411        // but guard against overflow.
 412  
 413  
 414        var handledCPCountPlusOne = handledCPCount + 1;
 415  
 416        if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
 417          error('overflow');
 418        }
 419  
 420        delta += (m - n) * handledCPCountPlusOne;
 421        n = m;
 422  
 423        for (var _iterator3 = _createForOfIteratorHelperLoose(input), _step3; !(_step3 = _iterator3()).done;) {
 424          var _currentValue = _step3.value;
 425  
 426          if (_currentValue < n && ++delta > maxInt) {
 427            error('overflow');
 428          }
 429  
 430          if (_currentValue == n) {
 431            // Represent delta as a generalized variable-length integer.
 432            var q = delta;
 433  
 434            for (var k = base;; k += base) {
 435              var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
 436  
 437              if (q < t) {
 438                break;
 439              }
 440  
 441              var qMinusT = q - t;
 442              var baseMinusT = base - t;
 443              output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
 444              q = floor(qMinusT / baseMinusT);
 445            }
 446  
 447            output.push(stringFromCharCode(digitToBasic(q, 0)));
 448            bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
 449            delta = 0;
 450            ++handledCPCount;
 451          }
 452        }
 453  
 454        ++delta;
 455        ++n;
 456      }
 457  
 458      return output.join('');
 459    };
 460    /**
 461     * Converts a Punycode string representing a domain name or an email address
 462     * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 463     * it doesn't matter if you call it on a string that has already been
 464     * converted to Unicode.
 465     * @memberOf punycode
 466     * @param {String} input The Punycoded domain name or email address to
 467     * convert to Unicode.
 468     * @returns {String} The Unicode representation of the given Punycode
 469     * string.
 470     */
 471  
 472  
 473    var toUnicode = function toUnicode(input) {
 474      return mapDomain(input, function (string) {
 475        return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
 476      });
 477    };
 478    /**
 479     * Converts a Unicode string representing a domain name or an email address to
 480     * Punycode. Only the non-ASCII parts of the domain name will be converted,
 481     * i.e. it doesn't matter if you call it with a domain that's already in
 482     * ASCII.
 483     * @memberOf punycode
 484     * @param {String} input The domain name or email address to convert, as a
 485     * Unicode string.
 486     * @returns {String} The Punycode representation of the given domain name or
 487     * email address.
 488     */
 489  
 490  
 491    var toASCII = function toASCII(input) {
 492      return mapDomain(input, function (string) {
 493        return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
 494      });
 495    };
 496    /*--------------------------------------------------------------------------*/
 497  
 498    /** Define the public API */
 499  
 500  
 501    var punycode = {
 502      /**
 503       * A string representing the current Punycode.js version number.
 504       * @memberOf punycode
 505       * @type String
 506       */
 507      'version': '2.1.0',
 508  
 509      /**
 510       * An object of methods to convert from JavaScript's internal character
 511       * representation (UCS-2) to Unicode code points, and back.
 512       * @see <https://mathiasbynens.be/notes/javascript-encoding>
 513       * @memberOf punycode
 514       * @type Object
 515       */
 516      'ucs2': {
 517        'decode': ucs2decode,
 518        'encode': ucs2encode
 519      },
 520      'decode': decode,
 521      'encode': encode,
 522      'toASCII': toASCII,
 523      'toUnicode': toUnicode
 524    };
 525    /**
 526     * @copyright  (C) 2018 Open Source Matters, Inc. <https://www.joomla.org>
 527     * @license    GNU General Public License version 2 or later; see LICENSE.txt
 528     */
 529  
 530    var JFormValidator = /*#__PURE__*/function () {
 531      function JFormValidator() {
 532        var _this = this;
 533  
 534        this.customValidators = {};
 535        this.handlers = [];
 536        this.handlers = {};
 537        this.removeMarking = this.removeMarking.bind(this);
 538  
 539        this.inputEmail = function () {
 540          var input = document.createElement('input');
 541          input.setAttribute('type', 'email');
 542          return input.type !== 'text';
 543        }; // Default handlers
 544  
 545  
 546        this.setHandler('username', function (value) {
 547          var regex = /[<|>|"|'|%|;|(|)|&]/i;
 548          return !regex.test(value);
 549        });
 550        this.setHandler('password', function (value) {
 551          var regex = /^\S[\S ]{2,98}\S$/;
 552          return regex.test(value);
 553        });
 554        this.setHandler('numeric', function (value) {
 555          var regex = /^(\d|-)?(\d|,)*\.?\d*$/;
 556          return regex.test(value);
 557        });
 558        this.setHandler('email', function (value) {
 559          var newValue = punycode.toASCII(value);
 560          var regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
 561          return regex.test(newValue);
 562        }); // Attach all forms with a class 'form-validate'
 563  
 564        var forms = [].slice.call(document.querySelectorAll('form'));
 565        forms.forEach(function (form) {
 566          if (form.classList.contains('form-validate')) {
 567            _this.attachToForm(form);
 568          }
 569        });
 570      }
 571  
 572      var _proto = JFormValidator.prototype;
 573  
 574      _proto.setHandler = function setHandler(name, func, en) {
 575        var isEnabled = en === '' ? true : en;
 576        this.handlers[name] = {
 577          enabled: isEnabled,
 578          exec: func
 579        };
 580      } // eslint-disable-next-line class-methods-use-this
 581      ;
 582  
 583      _proto.markValid = function markValid(element) {
 584        // Get a label
 585        var label = element.form.querySelector("label[for=\"" + element.id + "\"]");
 586        var message;
 587  
 588        if (element.classList.contains('required') || element.getAttribute('required')) {
 589          if (label) {
 590            message = label.querySelector('span.form-control-feedback');
 591          }
 592        }
 593  
 594        element.classList.remove('form-control-danger');
 595        element.classList.remove('invalid');
 596        element.classList.add('form-control-success');
 597        element.parentNode.classList.remove('has-danger');
 598        element.parentNode.classList.add('has-success');
 599        element.setAttribute('aria-invalid', 'false'); // Remove message
 600  
 601        if (message) {
 602          message.parentNode.removeChild(message);
 603        } // Restore Label
 604  
 605  
 606        if (label) {
 607          label.classList.remove('invalid');
 608        }
 609      } // eslint-disable-next-line class-methods-use-this
 610      ;
 611  
 612      _proto.markInvalid = function markInvalid(element, empty) {
 613        // Get a label
 614        var label = element.form.querySelector("label[for=\"" + element.id + "\"]");
 615        element.classList.remove('form-control-success');
 616        element.classList.remove('valid');
 617        element.classList.add('form-control-danger');
 618        element.classList.add('invalid');
 619        element.parentNode.classList.remove('has-success');
 620        element.parentNode.classList.add('has-danger');
 621        element.setAttribute('aria-invalid', 'true'); // Display custom message
 622  
 623        var mesgCont;
 624        var message = element.getAttribute('data-validation-text');
 625  
 626        if (label) {
 627          mesgCont = label.querySelector('span.form-control-feedback');
 628        }
 629  
 630        if (!mesgCont) {
 631          var elMsg = document.createElement('span');
 632          elMsg.classList.add('form-control-feedback');
 633  
 634          if (empty && empty === 'checkbox') {
 635            elMsg.innerHTML = message !== null ? Joomla.sanitizeHtml(message) : Joomla.sanitizeHtml(Joomla.Text._('JLIB_FORM_FIELD_REQUIRED_CHECK'));
 636          } else if (empty && empty === 'value') {
 637            elMsg.innerHTML = message !== null ? Joomla.sanitizeHtml(message) : Joomla.sanitizeHtml(Joomla.Text._('JLIB_FORM_FIELD_REQUIRED_VALUE'));
 638          } else {
 639            elMsg.innerHTML = message !== null ? Joomla.sanitizeHtml(message) : Joomla.sanitizeHtml(Joomla.Text._('JLIB_FORM_FIELD_INVALID_VALUE'));
 640          }
 641  
 642          if (label) {
 643            label.appendChild(elMsg);
 644          }
 645        } // Mark the Label as well
 646  
 647  
 648        if (label) {
 649          label.classList.add('invalid');
 650        }
 651      } // eslint-disable-next-line class-methods-use-this
 652      ;
 653  
 654      _proto.removeMarking = function removeMarking(element) {
 655        // Get the associated label
 656        var message;
 657        var label = element.form.querySelector("label[for=\"" + element.id + "\"]");
 658  
 659        if (label) {
 660          message = label.querySelector('span.form-control-feedback');
 661        }
 662  
 663        element.classList.remove('form-control-danger');
 664        element.classList.remove('form-control-success');
 665        element.classList.remove('invalid');
 666        element.classList.add('valid');
 667        element.parentNode.classList.remove('has-danger');
 668        element.parentNode.classList.remove('has-success'); // Remove message
 669  
 670        if (message) {
 671          if (label) {
 672            label.removeChild(message);
 673          }
 674        } // Restore Label
 675  
 676  
 677        if (label) {
 678          label.classList.remove('invalid');
 679        }
 680      };
 681  
 682      _proto.handleResponse = function handleResponse(state, element, empty) {
 683        var tagName = element.tagName.toLowerCase(); // Set the element and its label (if exists) invalid state
 684  
 685        if (tagName !== 'button' && element.value !== undefined || tagName === 'fieldset') {
 686          if (state === false) {
 687            this.markInvalid(element, empty);
 688          } else {
 689            this.markValid(element);
 690          }
 691        }
 692      };
 693  
 694      _proto.validate = function validate(element) {
 695        var tagName; // Ignore the element if its currently disabled,
 696        // because are not submitted for the http-request.
 697        // For those case return always true.
 698  
 699        if (element.getAttribute('disabled') === 'disabled' || element.getAttribute('display') === 'none') {
 700          this.handleResponse(true, element);
 701          return true;
 702        } // If the field is required make sure it has a value
 703  
 704  
 705        if (element.getAttribute('required') || element.classList.contains('required')) {
 706          tagName = element.tagName.toLowerCase();
 707  
 708          if (tagName === 'fieldset' && (element.classList.contains('radio') || element.classList.contains('checkboxes'))) {
 709            // No options are checked.
 710            if (element.querySelector('input:checked') === null) {
 711              this.handleResponse(false, element, 'checkbox');
 712              return false;
 713            }
 714          } else if (element.getAttribute('type') === 'checkbox' && element.checked !== true || tagName === 'select' && !element.value.length) {
 715            this.handleResponse(false, element, 'checkbox');
 716            return false;
 717          } else if (!element.value || element.classList.contains('placeholder')) {
 718            // If element has class placeholder that means it is empty.
 719            this.handleResponse(false, element, 'value');
 720            return false;
 721          }
 722        } // Only validate the field if the validate class is set
 723  
 724  
 725        var handler = element.getAttribute('class') && element.getAttribute('class').match(/validate-([a-zA-Z0-9_-]+)/) ? element.getAttribute('class').match(/validate-([a-zA-Z0-9_-]+)/)[1] : '';
 726  
 727        if (element.getAttribute('pattern') && element.getAttribute('pattern') !== '') {
 728          if (element.value.length) {
 729            var isValid = new RegExp("^" + element.getAttribute('pattern') + "$").test(element.value);
 730            this.handleResponse(isValid, element, 'empty');
 731            return isValid;
 732          }
 733  
 734          if (element.hasAttribute('required') || element.classList.contains('required')) {
 735            this.handleResponse(false, element, 'empty');
 736            return false;
 737          }
 738  
 739          this.handleResponse(true, element);
 740          return true;
 741        }
 742  
 743        if (handler === '') {
 744          this.handleResponse(true, element);
 745          return true;
 746        } // Check the additional validation types
 747  
 748  
 749        if (handler && handler !== 'none' && this.handlers[handler] && element.value) {
 750          // Execute the validation handler and return result
 751          if (this.handlers[handler].exec(element.value, element) !== true) {
 752            this.handleResponse(false, element, 'invalid_value');
 753            return false;
 754          }
 755        } // Return validation state
 756  
 757  
 758        this.handleResponse(true, element);
 759        return true;
 760      };
 761  
 762      _proto.isValid = function isValid(form) {
 763        var _this2 = this;
 764  
 765        var valid = true;
 766        var message;
 767        var error;
 768        var invalid = []; // Validate form fields
 769  
 770        var fields = [].slice.call(form.querySelectorAll('input, textarea, select, button, fieldset'));
 771        fields.forEach(function (field) {
 772          if (_this2.validate(field) === false) {
 773            valid = false;
 774            invalid.push(field);
 775          }
 776        }); // Run custom form validators if present
 777  
 778        if (Object.keys(this.customValidators).length) {
 779          Object.keys(this.customValidators).foreach(function (key) {
 780            if (_this2.customValidators[key].exec() !== true) {
 781              valid = false;
 782            }
 783          });
 784        }
 785  
 786        if (!valid && invalid.length > 0) {
 787          if (form.getAttribute('data-validation-text')) {
 788            message = form.getAttribute('data-validation-text');
 789          } else {
 790            message = Joomla.Text._('JLIB_FORM_CONTAINS_INVALID_FIELDS');
 791          }
 792  
 793          error = {
 794            error: [message]
 795          };
 796          Joomla.renderMessages(error);
 797        }
 798  
 799        return valid;
 800      };
 801  
 802      _proto.attachToForm = function attachToForm(form) {
 803        var _this3 = this;
 804  
 805        var elements = [].slice.call(form.querySelectorAll('input, textarea, select, button, fieldset')); // Iterate through the form object and attach the validate method to all input fields.
 806  
 807        elements.forEach(function (element) {
 808          var tagName = element.tagName.toLowerCase();
 809  
 810          if (['input', 'textarea', 'select', 'fieldset'].indexOf(tagName) > -1 && element.classList.contains('required')) {
 811            element.setAttribute('required', '');
 812          } // Attach isValid method to submit button
 813  
 814  
 815          if ((tagName === 'input' || tagName === 'button') && (element.getAttribute('type') === 'submit' || element.getAttribute('type') === 'image')) {
 816            if (element.classList.contains('validate')) {
 817              element.addEventListener('click', function () {
 818                return _this3.isValid(form);
 819              });
 820            }
 821          } else if (tagName !== 'button' && !(tagName === 'input' && element.getAttribute('type') === 'button')) {
 822            // Attach validate method only to fields
 823            if (tagName !== 'fieldset') {
 824              element.addEventListener('blur', function (_ref) {
 825                var target = _ref.target;
 826                return _this3.validate(target);
 827              });
 828              element.addEventListener('focus', function (_ref2) {
 829                var target = _ref2.target;
 830                return _this3.removeMarking(target);
 831              });
 832  
 833              if (element.classList.contains('validate-email') && _this3.inputEmail) {
 834                element.setAttribute('type', 'email');
 835              }
 836            }
 837          }
 838        });
 839      };
 840  
 841      _createClass(JFormValidator, [{
 842        key: "custom",
 843        get: function get() {
 844          return this.customValidators;
 845        },
 846        set: function set(value) {
 847          this.customValidators = value;
 848        }
 849      }]);
 850  
 851      return JFormValidator;
 852    }();
 853  
 854    var initialize = function initialize() {
 855      document.formvalidator = new JFormValidator(); // Cleanup
 856  
 857      document.removeEventListener('DOMContentLoaded', initialize);
 858    };
 859  
 860    document.addEventListener('DOMContentLoaded', initialize);
 861  
 862  })();


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer