Skip to content
parsley.js 92.8 KiB
Newer Older
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
        message: message,
        assert: assert
      });

      if (updateClass) this._errorClass();
    },
    // It's a goal of Parsley that this method is no longer required [#1073]
    updateError: function updateError(name) {
      var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
          message = _ref2.message,
          assert = _ref2.assert,
          _ref2$updateClass = _ref2.updateClass,
          updateClass = _ref2$updateClass === void 0 ? true : _ref2$updateClass;

      this._buildUI();

      this._updateError(name, {
        message: message,
        assert: assert
      });

      if (updateClass) this._errorClass();
    },
    // It's a goal of Parsley that this method is no longer required [#1073]
    removeError: function removeError(name) {
      var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
          _ref3$updateClass = _ref3.updateClass,
          updateClass = _ref3$updateClass === void 0 ? true : _ref3$updateClass;

      this._buildUI();

      this._removeError(name); // edge case possible here: remove a standard Parsley error that is still failing in this.validationResult
      // but highly improbable cuz' manually removing a well Parsley handled error makes no sense.


      if (updateClass) this._manageStatusClass();
    },
    _manageStatusClass: function _manageStatusClass() {
      if (this.hasConstraints() && this.needsValidation() && true === this.validationResult) this._successClass();else if (this.validationResult.length > 0) this._errorClass();else this._resetClass();
    },
    _manageErrorsMessages: function _manageErrorsMessages(diff) {
      if ('undefined' !== typeof this.options.errorsMessagesDisabled) return; // Case where we have errorMessage option that configure an unique field error message, regardless failing validators

      if ('undefined' !== typeof this.options.errorMessage) {
        if (diff.added.length || diff.kept.length) {
          this._insertErrorWrapper();

          if (0 === this._ui.$errorsWrapper.find('.parsley-custom-error-message').length) this._ui.$errorsWrapper.append($(this.options.errorTemplate).addClass('parsley-custom-error-message'));

          this._ui.$errorClassHandler.attr('aria-describedby', this._ui.errorsWrapperId);

          return this._ui.$errorsWrapper.addClass('filled').attr('aria-hidden', 'false').find('.parsley-custom-error-message').html(this.options.errorMessage);
        }

        this._ui.$errorClassHandler.removeAttr('aria-describedby');

        return this._ui.$errorsWrapper.removeClass('filled').attr('aria-hidden', 'true').find('.parsley-custom-error-message').remove();
      } // Show, hide, update failing constraints messages


      for (var i = 0; i < diff.removed.length; i++) {
        this._removeError(diff.removed[i].assert.name);
      }

      for (i = 0; i < diff.added.length; i++) {
        this._addError(diff.added[i].assert.name, {
          message: diff.added[i].errorMessage,
          assert: diff.added[i].assert
        });
      }

      for (i = 0; i < diff.kept.length; i++) {
        this._updateError(diff.kept[i].assert.name, {
          message: diff.kept[i].errorMessage,
          assert: diff.kept[i].assert
        });
      }
    },
    _addError: function _addError(name, _ref4) {
      var message = _ref4.message,
          assert = _ref4.assert;

      this._insertErrorWrapper();

      this._ui.$errorClassHandler.attr('aria-describedby', this._ui.errorsWrapperId);

      this._ui.$errorsWrapper.addClass('filled').attr('aria-hidden', 'false').append($(this.options.errorTemplate).addClass('parsley-' + name).html(message || this._getErrorMessage(assert)));
    },
    _updateError: function _updateError(name, _ref5) {
      var message = _ref5.message,
          assert = _ref5.assert;

      this._ui.$errorsWrapper.addClass('filled').find('.parsley-' + name).html(message || this._getErrorMessage(assert));
    },
    _removeError: function _removeError(name) {
      this._ui.$errorClassHandler.removeAttr('aria-describedby');

      this._ui.$errorsWrapper.removeClass('filled').attr('aria-hidden', 'true').find('.parsley-' + name).remove();
    },
    _getErrorMessage: function _getErrorMessage(constraint) {
      var customConstraintErrorMessage = constraint.name + 'Message';
      if ('undefined' !== typeof this.options[customConstraintErrorMessage]) return window.Parsley.formatMessage(this.options[customConstraintErrorMessage], constraint.requirements);
      return window.Parsley.getErrorMessage(constraint);
    },
    _buildUI: function _buildUI() {
      // UI could be already built or disabled
      if (this._ui || false === this.options.uiEnabled) return;
      var _ui = {}; // Give field its Parsley id in DOM

      this.element.setAttribute(this.options.namespace + 'id', this.__id__);
      /** Generate important UI elements and store them in this **/
      // $errorClassHandler is the $element that woul have parsley-error and parsley-success classes

      _ui.$errorClassHandler = this._manageClassHandler(); // $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer

      _ui.errorsWrapperId = 'parsley-id-' + (this.options.multiple ? 'multiple-' + this.options.multiple : this.__id__);
      _ui.$errorsWrapper = $(this.options.errorsWrapper).attr('id', _ui.errorsWrapperId); // ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly

      _ui.lastValidationResult = [];
      _ui.validationInformationVisible = false; // Store it in this for later

      this._ui = _ui;
    },
    // Determine which element will have `parsley-error` and `parsley-success` classes
    _manageClassHandler: function _manageClassHandler() {
      // Class handled could also be determined by function given in Parsley options
      if ('string' === typeof this.options.classHandler && $(this.options.classHandler).length) return $(this.options.classHandler); // Class handled could also be determined by function given in Parsley options

      var $handlerFunction = this.options.classHandler; // It might also be the function name of a global function

      if ('string' === typeof this.options.classHandler && 'function' === typeof window[this.options.classHandler]) $handlerFunction = window[this.options.classHandler];

      if ('function' === typeof $handlerFunction) {
        var $handler = $handlerFunction.call(this, this); // If this function returned a valid existing DOM element, go for it

        if ('undefined' !== typeof $handler && $handler.length) return $handler;
      } else if ('object' === _typeof($handlerFunction) && $handlerFunction instanceof jQuery && $handlerFunction.length) {
        return $handlerFunction;
      } else if ($handlerFunction) {
        Utils.warn('The class handler `' + $handlerFunction + '` does not exist in DOM nor as a global JS function');
      }

      return this._inputHolder();
    },
    _inputHolder: function _inputHolder() {
      // if simple element (input, texatrea, select...) it will perfectly host the classes and precede the error container
      if (!this.options.multiple || this.element.nodeName === 'SELECT') return this.$element; // But if multiple element (radio, checkbox), that would be their parent

      return this.$element.parent();
    },
    _insertErrorWrapper: function _insertErrorWrapper() {
      var $errorsContainer = this.options.errorsContainer; // Nothing to do if already inserted

      if (0 !== this._ui.$errorsWrapper.parent().length) return this._ui.$errorsWrapper.parent();

      if ('string' === typeof $errorsContainer) {
        if ($($errorsContainer).length) return $($errorsContainer).append(this._ui.$errorsWrapper);else if ('function' === typeof window[$errorsContainer]) $errorsContainer = window[$errorsContainer];else Utils.warn('The errors container `' + $errorsContainer + '` does not exist in DOM nor as a global JS function');
      }

      if ('function' === typeof $errorsContainer) $errorsContainer = $errorsContainer.call(this, this);
      if ('object' === _typeof($errorsContainer) && $errorsContainer.length) return $errorsContainer.append(this._ui.$errorsWrapper);
      return this._inputHolder().after(this._ui.$errorsWrapper);
    },
    _actualizeTriggers: function _actualizeTriggers() {
      var _this2 = this;

      var $toBind = this._findRelated();

      var trigger; // Remove Parsley events already bound on this field

      $toBind.off('.Parsley');
      if (this._failedOnce) $toBind.on(Utils.namespaceEvents(this.options.triggerAfterFailure, 'Parsley'), function () {
        _this2._validateIfNeeded();
      });else if (trigger = Utils.namespaceEvents(this.options.trigger, 'Parsley')) {
        $toBind.on(trigger, function (event) {
          _this2._validateIfNeeded(event);
        });
      }
    },
    _validateIfNeeded: function _validateIfNeeded(event) {
      var _this3 = this;

      // For keyup, keypress, keydown, input... events that could be a little bit obstrusive
      // do not validate if val length < min threshold on first validation. Once field have been validated once and info
      // about success or failure have been displayed, always validate with this trigger to reflect every yalidation change.
      if (event && /key|input/.test(event.type)) if (!(this._ui && this._ui.validationInformationVisible) && this.getValue().length <= this.options.validationThreshold) return;

      if (this.options.debounce) {
        window.clearTimeout(this._debounced);
        this._debounced = window.setTimeout(function () {
          return _this3.validate();
        }, this.options.debounce);
      } else this.validate();
    },
    _resetUI: function _resetUI() {
      // Reset all event listeners
      this._failedOnce = false;

      this._actualizeTriggers(); // Nothing to do if UI never initialized for this field


      if ('undefined' === typeof this._ui) return; // Reset all errors' li

      this._ui.$errorsWrapper.removeClass('filled').children().remove(); // Reset validation class


      this._resetClass(); // Reset validation flags and last validation result


      this._ui.lastValidationResult = [];
      this._ui.validationInformationVisible = false;
    },
    _destroyUI: function _destroyUI() {
      this._resetUI();

      if ('undefined' !== typeof this._ui) this._ui.$errorsWrapper.remove();
      delete this._ui;
    },
    _successClass: function _successClass() {
      this._ui.validationInformationVisible = true;

      this._ui.$errorClassHandler.removeClass(this.options.errorClass).addClass(this.options.successClass);
    },
    _errorClass: function _errorClass() {
      this._ui.validationInformationVisible = true;

      this._ui.$errorClassHandler.removeClass(this.options.successClass).addClass(this.options.errorClass);
    },
    _resetClass: function _resetClass() {
      this._ui.$errorClassHandler.removeClass(this.options.successClass).removeClass(this.options.errorClass);
    }
  };

  var Form = function Form(element, domOptions, options) {
    this.__class__ = 'Form';
    this.element = element;
    this.$element = $(element);
    this.domOptions = domOptions;
    this.options = options;
    this.parent = window.Parsley;
    this.fields = [];
    this.validationResult = null;
  };

  var statusMapping = {
    pending: null,
    resolved: true,
    rejected: false
  };
  Form.prototype = {
    onSubmitValidate: function onSubmitValidate(event) {
      var _this = this;

      // This is a Parsley generated submit event, do not validate, do not prevent, simply exit and keep normal behavior
      if (true === event.parsley) return; // If we didn't come here through a submit button, use the first one in the form

      var submitSource = this._submitSource || this.$element.find(Utils._SubmitSelector)[0];
      this._submitSource = null;
      this.$element.find('.parsley-synthetic-submit-button').prop('disabled', true);
      if (submitSource && null !== submitSource.getAttribute('formnovalidate')) return;
      window.Parsley._remoteCache = {};
      var promise = this.whenValidate({
        event: event
      });

      if ('resolved' === promise.state() && false !== this._trigger('submit')) ; else {
        // Rejected or pending: cancel this submit
        event.stopImmediatePropagation();
        event.preventDefault();
        if ('pending' === promise.state()) promise.done(function () {
          _this._submit(submitSource);
        });
      }
    },
    onSubmitButton: function onSubmitButton(event) {
      this._submitSource = event.currentTarget;
    },
    // internal
    // _submit submits the form, this time without going through the validations.
    // Care must be taken to "fake" the actual submit button being clicked.
    _submit: function _submit(submitSource) {
      if (false === this._trigger('submit')) return; // Add submit button's data

      if (submitSource) {
        var $synthetic = this.$element.find('.parsley-synthetic-submit-button').prop('disabled', false);
        if (0 === $synthetic.length) $synthetic = $('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element);
        $synthetic.attr({
          name: submitSource.getAttribute('name'),
          value: submitSource.getAttribute('value')
        });
      }

      this.$element.trigger(_extends($.Event('submit'), {
        parsley: true
      }));
    },
    // Performs validation on fields while triggering events.
    // @returns `true` if all validations succeeds, `false`
    // if a failure is immediately detected, or `null`
    // if dependant on a promise.
    // Consider using `whenValidate` instead.
    validate: function validate(options) {
      if (arguments.length >= 1 && !$.isPlainObject(options)) {
        Utils.warnOnce('Calling validate on a parsley form without passing arguments as an object is deprecated.');

        var _arguments = Array.prototype.slice.call(arguments),
            group = _arguments[0],
            force = _arguments[1],
            event = _arguments[2];

        options = {
          group: group,
          force: force,
          event: event
        };
      }

      return statusMapping[this.whenValidate(options).state()];
    },
    whenValidate: function whenValidate() {
      var _this2 = this,
          _Utils$all$done$fail$;

      var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          group = _ref.group,
          force = _ref.force,
          event = _ref.event;

      this.submitEvent = event;

      if (event) {
        this.submitEvent = _extends({}, event, {
          preventDefault: function preventDefault() {
            Utils.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`");
            _this2.validationResult = false;
          }
        });
      }

      this.validationResult = true; // fire validate event to eventually modify things before every validation

      this._trigger('validate'); // Refresh form DOM options and form's fields that could have changed


      this._refreshFields();

      var promises = this._withoutReactualizingFormOptions(function () {
        return $.map(_this2.fields, function (field) {
          return field.whenValidate({
            force: force,
            group: group
          });
        });
      });

      return (_Utils$all$done$fail$ = Utils.all(promises).done(function () {
        _this2._trigger('success');
      }).fail(function () {
        _this2.validationResult = false;

        _this2.focus();

        _this2._trigger('error');
      }).always(function () {
        _this2._trigger('validated');
      })).pipe.apply(_Utils$all$done$fail$, _toConsumableArray(this._pipeAccordingToValidationResult()));
    },
    // Iterate over refreshed fields, and stop on first failure.
    // Returns `true` if all fields are valid, `false` if a failure is detected
    // or `null` if the result depends on an unresolved promise.
    // Prefer using `whenValid` instead.
    isValid: function isValid(options) {
      if (arguments.length >= 1 && !$.isPlainObject(options)) {
        Utils.warnOnce('Calling isValid on a parsley form without passing arguments as an object is deprecated.');

        var _arguments2 = Array.prototype.slice.call(arguments),
            group = _arguments2[0],
            force = _arguments2[1];

        options = {
          group: group,
          force: force
        };
      }

      return statusMapping[this.whenValid(options).state()];
    },
    // Iterate over refreshed fields and validate them.
    // Returns a promise.
    // A validation that immediately fails will interrupt the validations.
    whenValid: function whenValid() {
      var _this3 = this;

      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          group = _ref2.group,
          force = _ref2.force;

      this._refreshFields();

      var promises = this._withoutReactualizingFormOptions(function () {
        return $.map(_this3.fields, function (field) {
          return field.whenValid({
            group: group,
            force: force
          });
        });
      });

      return Utils.all(promises);
    },
    refresh: function refresh() {
      this._refreshFields();

      return this;
    },
    // Reset UI
    reset: function reset() {
      // Form case: emit a reset event for each field
      for (var i = 0; i < this.fields.length; i++) {
        this.fields[i].reset();
      }

      this._trigger('reset');
    },
    // Destroy Parsley instance (+ UI)
    destroy: function destroy() {
      // Field case: emit destroy event to clean UI and then destroy stored instance
      this._destroyUI(); // Form case: destroy all its fields and then destroy stored instance


      for (var i = 0; i < this.fields.length; i++) {
        this.fields[i].destroy();
      }

      this.$element.removeData('Parsley');

      this._trigger('destroy');
    },
    _refreshFields: function _refreshFields() {
      return this.actualizeOptions()._bindFields();
    },
    _bindFields: function _bindFields() {
      var _this4 = this;

      var oldFields = this.fields;
      this.fields = [];
      this.fieldsMappedById = {};

      this._withoutReactualizingFormOptions(function () {
        _this4.$element.find(_this4.options.inputs).not(_this4.options.excluded).not("[".concat(_this4.options.namespace, "excluded=true]")).each(function (_, element) {
          var fieldInstance = new window.Parsley.Factory(element, {}, _this4); // Only add valid and not excluded `Field` and `FieldMultiple` children

          if ('Field' === fieldInstance.__class__ || 'FieldMultiple' === fieldInstance.__class__) {
            var uniqueId = fieldInstance.__class__ + '-' + fieldInstance.__id__;

            if ('undefined' === typeof _this4.fieldsMappedById[uniqueId]) {
              _this4.fieldsMappedById[uniqueId] = fieldInstance;

              _this4.fields.push(fieldInstance);
            }
          }
        });

        $.each(Utils.difference(oldFields, _this4.fields), function (_, field) {
          field.reset();
        });
      });

      return this;
    },
    // Internal only.
    // Looping on a form's fields to do validation or similar
    // will trigger reactualizing options on all of them, which
    // in turn will reactualize the form's options.
    // To avoid calling actualizeOptions so many times on the form
    // for nothing, _withoutReactualizingFormOptions temporarily disables
    // the method actualizeOptions on this form while `fn` is called.
    _withoutReactualizingFormOptions: function _withoutReactualizingFormOptions(fn) {
      var oldActualizeOptions = this.actualizeOptions;

      this.actualizeOptions = function () {
        return this;
      };

      var result = fn();
      this.actualizeOptions = oldActualizeOptions;
      return result;
    },
    // Internal only.
    // Shortcut to trigger an event
    // Returns true iff event is not interrupted and default not prevented.
    _trigger: function _trigger(eventName) {
      return this.trigger('form:' + eventName);
    }
  };

  var Constraint = function Constraint(parsleyField, name, requirements, priority, isDomConstraint) {
    var validatorSpec = window.Parsley._validatorRegistry.validators[name];
    var validator = new Validator(validatorSpec);
    priority = priority || parsleyField.options[name + 'Priority'] || validator.priority;
    isDomConstraint = true === isDomConstraint;

    _extends(this, {
      validator: validator,
      name: name,
      requirements: requirements,
      priority: priority,
      isDomConstraint: isDomConstraint
    });

    this._parseRequirements(parsleyField.options);
  };

  var capitalize = function capitalize(str) {
    var cap = str[0].toUpperCase();
    return cap + str.slice(1);
  };

  Constraint.prototype = {
    validate: function validate(value, instance) {
      var _this$validator;

      return (_this$validator = this.validator).validate.apply(_this$validator, [value].concat(_toConsumableArray(this.requirementList), [instance]));
    },
    _parseRequirements: function _parseRequirements(options) {
      var _this = this;

      this.requirementList = this.validator.parseRequirements(this.requirements, function (key) {
        return options[_this.name + capitalize(key)];
      });
    }
  };

  var Field = function Field(field, domOptions, options, parsleyFormInstance) {
    this.__class__ = 'Field';
    this.element = field;
    this.$element = $(field); // Set parent if we have one

    if ('undefined' !== typeof parsleyFormInstance) {
      this.parent = parsleyFormInstance;
    }

    this.options = options;
    this.domOptions = domOptions; // Initialize some properties

    this.constraints = [];
    this.constraintsByName = {};
    this.validationResult = true; // Bind constraints

    this._bindConstraints();
  };

  var statusMapping$1 = {
    pending: null,
    resolved: true,
    rejected: false
  };
  Field.prototype = {
    // # Public API
    // Validate field and trigger some events for mainly `UI`
    // @returns `true`, an array of the validators that failed, or
    // `null` if validation is not finished. Prefer using whenValidate
    validate: function validate(options) {
      if (arguments.length >= 1 && !$.isPlainObject(options)) {
        Utils.warnOnce('Calling validate on a parsley field without passing arguments as an object is deprecated.');
        options = {
          options: options
        };
      }

      var promise = this.whenValidate(options);
      if (!promise) // If excluded with `group` option
        return true;

      switch (promise.state()) {
        case 'pending':
          return null;

        case 'resolved':
          return true;

        case 'rejected':
          return this.validationResult;
      }
    },
    // Validate field and trigger some events for mainly `UI`
    // @returns a promise that succeeds only when all validations do
    // or `undefined` if field is not in the given `group`.
    whenValidate: function whenValidate() {
      var _this$whenValid$alway,
          _this = this;

      var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          force = _ref.force,
          group = _ref.group;

      // do not validate a field if not the same as given validation group
      this.refresh();
      if (group && !this._isInGroup(group)) return;
      this.value = this.getValue(); // Field Validate event. `this.value` could be altered for custom needs

      this._trigger('validate');

      return (_this$whenValid$alway = this.whenValid({
        force: force,
        value: this.value,
        _refreshed: true
      }).always(function () {
        _this._reflowUI();
      }).done(function () {
        _this._trigger('success');
      }).fail(function () {
        _this._trigger('error');
      }).always(function () {
        _this._trigger('validated');
      })).pipe.apply(_this$whenValid$alway, _toConsumableArray(this._pipeAccordingToValidationResult()));
    },
    hasConstraints: function hasConstraints() {
      return 0 !== this.constraints.length;
    },
    // An empty optional field does not need validation
    needsValidation: function needsValidation(value) {
      if ('undefined' === typeof value) value = this.getValue(); // If a field is empty and not required, it is valid
      // Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators

      if (!value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty) return false;
      return true;
    },
    _isInGroup: function _isInGroup(group) {
      if (Array.isArray(this.options.group)) return -1 !== $.inArray(group, this.options.group);
      return this.options.group === group;
    },
    // Just validate field. Do not trigger any event.
    // Returns `true` iff all constraints pass, `false` if there are failures,
    // or `null` if the result can not be determined yet (depends on a promise)
    // See also `whenValid`.
    isValid: function isValid(options) {
      if (arguments.length >= 1 && !$.isPlainObject(options)) {
        Utils.warnOnce('Calling isValid on a parsley field without passing arguments as an object is deprecated.');

        var _arguments = Array.prototype.slice.call(arguments),
            force = _arguments[0],
            value = _arguments[1];

        options = {
          force: force,
          value: value
        };
      }

      var promise = this.whenValid(options);
      if (!promise) // Excluded via `group`
        return true;
      return statusMapping$1[promise.state()];
    },
    // Just validate field. Do not trigger any event.
    // @returns a promise that succeeds only when all validations do
    // or `undefined` if the field is not in the given `group`.
    // The argument `force` will force validation of empty fields.
    // If a `value` is given, it will be validated instead of the value of the input.
    whenValid: function whenValid() {
      var _this2 = this;

      var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
          _ref2$force = _ref2.force,
          force = _ref2$force === void 0 ? false : _ref2$force,
          value = _ref2.value,
          group = _ref2.group,
          _refreshed = _ref2._refreshed;

      // Recompute options and rebind constraints to have latest changes
      if (!_refreshed) this.refresh(); // do not validate a field if not the same as given validation group

      if (group && !this._isInGroup(group)) return;
      this.validationResult = true; // A field without constraint is valid

      if (!this.hasConstraints()) return $.when(); // Value could be passed as argument, needed to add more power to 'field:validate'

      if ('undefined' === typeof value || null === value) value = this.getValue();
      if (!this.needsValidation(value) && true !== force) return $.when();

      var groupedConstraints = this._getGroupedConstraints();

      var promises = [];
      $.each(groupedConstraints, function (_, constraints) {
        // Process one group of constraints at a time, we validate the constraints
        // and combine the promises together.
        var promise = Utils.all($.map(constraints, function (constraint) {
          return _this2._validateConstraint(value, constraint);
        }));
        promises.push(promise);
        if (promise.state() === 'rejected') return false; // Interrupt processing if a group has already failed
      });
      return Utils.all(promises);
    },
    // @returns a promise
    _validateConstraint: function _validateConstraint(value, constraint) {
      var _this3 = this;

      var result = constraint.validate(value, this); // Map false to a failed promise

      if (false === result) result = $.Deferred().reject(); // Make sure we return a promise and that we record failures

      return Utils.all([result]).fail(function (errorMessage) {
        if (!(_this3.validationResult instanceof Array)) _this3.validationResult = [];

        _this3.validationResult.push({
          assert: constraint,
          errorMessage: 'string' === typeof errorMessage && errorMessage
        });
      });
    },
    // @returns Parsley field computed value that could be overrided or configured in DOM
    getValue: function getValue() {
      var value; // Value could be overriden in DOM or with explicit options

      if ('function' === typeof this.options.value) value = this.options.value(this);else if ('undefined' !== typeof this.options.value) value = this.options.value;else value = this.$element.val(); // Handle wrong DOM or configurations

      if ('undefined' === typeof value || null === value) return '';
      return this._handleWhitespace(value);
    },
    // Reset UI
    reset: function reset() {
      this._resetUI();

      return this._trigger('reset');
    },
    // Destroy Parsley instance (+ UI)
    destroy: function destroy() {
      // Field case: emit destroy event to clean UI and then destroy stored instance
      this._destroyUI();

      this.$element.removeData('Parsley');
      this.$element.removeData('FieldMultiple');

      this._trigger('destroy');
    },
    // Actualize options and rebind constraints
    refresh: function refresh() {
      this._refreshConstraints();

      return this;
    },
    _refreshConstraints: function _refreshConstraints() {
      return this.actualizeOptions()._bindConstraints();
    },
    refreshConstraints: function refreshConstraints() {
      Utils.warnOnce("Parsley's refreshConstraints is deprecated. Please use refresh");
      return this.refresh();
    },

    /**
    * Add a new constraint to a field
    *
    * @param {String}   name
    * @param {Mixed}    requirements      optional
    * @param {Number}   priority          optional
    * @param {Boolean}  isDomConstraint   optional
    */
    addConstraint: function addConstraint(name, requirements, priority, isDomConstraint) {
      if (window.Parsley._validatorRegistry.validators[name]) {
        var constraint = new Constraint(this, name, requirements, priority, isDomConstraint); // if constraint already exist, delete it and push new version

        if ('undefined' !== this.constraintsByName[constraint.name]) this.removeConstraint(constraint.name);
        this.constraints.push(constraint);
        this.constraintsByName[constraint.name] = constraint;
      }

      return this;
    },
    // Remove a constraint
    removeConstraint: function removeConstraint(name) {
      for (var i = 0; i < this.constraints.length; i++) {
        if (name === this.constraints[i].name) {
          this.constraints.splice(i, 1);
          break;
        }
      }

      delete this.constraintsByName[name];
      return this;
    },
    // Update a constraint (Remove + re-add)
    updateConstraint: function updateConstraint(name, parameters, priority) {
      return this.removeConstraint(name).addConstraint(name, parameters, priority);
    },
    // # Internals
    // Internal only.
    // Bind constraints from config + options + DOM
    _bindConstraints: function _bindConstraints() {
      var constraints = [];
      var constraintsByName = {}; // clean all existing DOM constraints to only keep javascript user constraints

      for (var i = 0; i < this.constraints.length; i++) {
        if (false === this.constraints[i].isDomConstraint) {
          constraints.push(this.constraints[i]);
          constraintsByName[this.constraints[i].name] = this.constraints[i];
        }
      }

      this.constraints = constraints;
      this.constraintsByName = constraintsByName; // then re-add Parsley DOM-API constraints

      for (var name in this.options) {
        this.addConstraint(name, this.options[name], undefined, true);
      } // finally, bind special HTML5 constraints


      return this._bindHtml5Constraints();
    },
    // Internal only.
    // Bind specific HTML5 constraints to be HTML5 compliant
    _bindHtml5Constraints: function _bindHtml5Constraints() {
      // html5 required
      if (null !== this.element.getAttribute('required')) this.addConstraint('required', true, undefined, true); // html5 pattern

      if (null !== this.element.getAttribute('pattern')) this.addConstraint('pattern', this.element.getAttribute('pattern'), undefined, true); // range

      var min = this.element.getAttribute('min');
      var max = this.element.getAttribute('max');
      if (null !== min && null !== max) this.addConstraint('range', [min, max], undefined, true); // HTML5 min
      else if (null !== min) this.addConstraint('min', min, undefined, true); // HTML5 max
        else if (null !== max) this.addConstraint('max', max, undefined, true); // length

      if (null !== this.element.getAttribute('minlength') && null !== this.element.getAttribute('maxlength')) this.addConstraint('length', [this.element.getAttribute('minlength'), this.element.getAttribute('maxlength')], undefined, true); // HTML5 minlength
      else if (null !== this.element.getAttribute('minlength')) this.addConstraint('minlength', this.element.getAttribute('minlength'), undefined, true); // HTML5 maxlength
        else if (null !== this.element.getAttribute('maxlength')) this.addConstraint('maxlength', this.element.getAttribute('maxlength'), undefined, true); // html5 types

      var type = Utils.getType(this.element); // Small special case here for HTML5 number: integer validator if step attribute is undefined or an integer value, number otherwise

      if ('number' === type) {
        return this.addConstraint('type', ['number', {
          step: this.element.getAttribute('step') || '1',
          base: min || this.element.getAttribute('value')
        }], undefined, true); // Regular other HTML5 supported types
      } else if (/^(email|url|range|date)$/i.test(type)) {
        return this.addConstraint('type', type, undefined, true);
      }

      return this;
    },
    // Internal only.
    // Field is required if have required constraint without `false` value
    _isRequired: function _isRequired() {
      if ('undefined' === typeof this.constraintsByName.required) return false;
      return false !== this.constraintsByName.required.requirements;
    },
    // Internal only.
    // Shortcut to trigger an event
    _trigger: function _trigger(eventName) {
      return this.trigger('field:' + eventName);
    },
    // Internal only
    // Handles whitespace in a value
    // Use `data-parsley-whitespace="squish"` to auto squish input value
    // Use `data-parsley-whitespace="trim"` to auto trim input value
    _handleWhitespace: function _handleWhitespace(value) {
      if (true === this.options.trimValue) Utils.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"');
      if ('squish' === this.options.whitespace) value = value.replace(/\s{2,}/g, ' ');
      if ('trim' === this.options.whitespace || 'squish' === this.options.whitespace || true === this.options.trimValue) value = Utils.trimString(value);
      return value;
    },
    _isDateInput: function _isDateInput() {
      var c = this.constraintsByName.type;
      return c && c.requirements === 'date';
    },
    // Internal only.
    // Returns the constraints, grouped by descending priority.
    // The result is thus an array of arrays of constraints.
    _getGroupedConstraints: function _getGroupedConstraints() {
      if (false === this.options.priorityEnabled) return [this.constraints];
      var groupedConstraints = [];
      var index = {}; // Create array unique of priorities

      for (var i = 0; i < this.constraints.length; i++) {
        var p = this.constraints[i].priority;
        if (!index[p]) groupedConstraints.push(index[p] = []);
        index[p].push(this.constraints[i]);
      } // Sort them by priority DESC


      groupedConstraints.sort(function (a, b) {
        return b[0].priority - a[0].priority;
      });
      return groupedConstraints;
    }
  };

  var Multiple = function Multiple() {
    this.__class__ = 'FieldMultiple';
  };

  Multiple.prototype = {
    // Add new `$element` sibling for multiple field
    addElement: function addElement($element) {
      this.$elements.push($element);
      return this;
    },
    // See `Field._refreshConstraints()`
    _refreshConstraints: function _refreshConstraints() {
      var fieldConstraints;
      this.constraints = []; // Select multiple special treatment

      if (this.element.nodeName === 'SELECT') {
        this.actualizeOptions()._bindConstraints();

        return this;
      } // Gather all constraints for each input in the multiple group


      for (var i = 0; i < this.$elements.length; i++) {
        // Check if element have not been dynamically removed since last binding
        if (!$('html').has(this.$elements[i]).length) {
          this.$elements.splice(i, 1);
          continue;
        }

        fieldConstraints = this.$elements[i].data('FieldMultiple')._refreshConstraints().constraints;

        for (var j = 0; j < fieldConstraints.length; j++) {
          this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint);
        }
      }

      return this;
    },
    // See `Field.getValue()`
    getValue: function getValue() {
      // Value could be overriden in DOM
      if ('function' === typeof this.options.value) return this.options.value(this);else if ('undefined' !== typeof this.options.value) return this.options.value; // Radio input case

      if (this.element.nodeName === 'INPUT') {
        var type = Utils.getType(this.element);
        if (type === 'radio') return this._findRelated().filter(':checked').val() || ''; // checkbox input case

        if (type === 'checkbox') {
          var values = [];

          this._findRelated().filter(':checked').each(function () {
            values.push($(this).val());
          });

          return values;
        }
      } // Select multiple case


      if (this.element.nodeName === 'SELECT' && null === this.$element.val()) return []; // Default case that should never happen

      return this.$element.val();
    },
    _init: function _init() {
      this.$elements = [this.$element];
      return this;
    }
  };

  var Factory = function Factory(element, options, parsleyFormInstance) {
    this.element = element;
    this.$element = $(element); // If the element has already been bound, returns its saved Parsley instance

    var savedparsleyFormInstance = this.$element.data('Parsley');

    if (savedparsleyFormInstance) {
      // If the saved instance has been bound without a Form parent and there is one given in this call, add it
      if ('undefined' !== typeof parsleyFormInstance && savedparsleyFormInstance.parent === window.Parsley) {
        savedparsleyFormInstance.parent = parsleyFormInstance;

        savedparsleyFormInstance._resetOptions(savedparsleyFormInstance.options);
      }

      if ('object' === _typeof(options)) {
        _extends(savedparsleyFormInstance.options, options);
      }

      return savedparsleyFormInstance;
    } // Parsley must be instantiated with a DOM element or jQuery $element


    if (!this.$element.length) throw new Error('You must bind Parsley on an existing element.');
    if ('undefined' !== typeof parsleyFormInstance && 'Form' !== parsleyFormInstance.__class__) throw new Error('Parent instance must be a Form instance');
    this.parent = parsleyFormInstance || window.Parsley;
    return this.init(options);
  };

  Factory.prototype = {
    init: function init(options) {
      this.__class__ = 'Parsley';
      this.__version__ = '2.9.2';
      this.__id__ = Utils.generateID(); // Pre-compute options

      this._resetOptions(options); // A Form instance is obviously a `<form>` element but also every node that is not an input and has the `data-parsley-validate` attribute


      if (this.element.nodeName === 'FORM' || Utils.checkAttr(this.element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs)) return this.bind('parsleyForm'); // Every other element is bound as a `Field` or `FieldMultiple`

      return this.isMultiple() ? this.handleMultiple() : this.bind('parsleyField');
    },
    isMultiple: function isMultiple() {
      var type = Utils.getType(this.element);