| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
16×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
6×
6×
6×
6×
6×
6×
6×
1×
6×
6×
6×
6×
6×
6×
6×
1×
2×
2×
2×
2×
2×
2×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
3×
3×
2×
2×
2×
3×
3×
3×
3×
1×
1×
1×
1×
1×
1×
1×
1×
1×
3×
3×
3×
3×
1×
1×
1×
1×
1×
1×
1×
3×
3×
3×
3×
1×
3×
2×
2×
2×
3×
3×
3×
3×
1×
1×
1×
1×
3×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
3×
1×
1×
1×
3×
3×
3×
19×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
6×
6×
6×
6×
1×
6×
1×
6×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
6×
6×
6×
1×
6×
6×
1×
1×
6×
1×
1×
1×
6×
1×
1×
6×
6×
6×
2×
6×
3×
2×
3×
1×
1×
1×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
2×
3×
3×
1×
1×
1×
1×
1×
1×
1×
5×
5×
5×
5×
1×
1×
1×
1×
1×
1×
1×
1×
| 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EVENT_FORM_AJAX_COMPLETED = exports.EVENT_FORM_AFTER_AJAX_SUBMIT = exports.EVENT_FORM_SUBMIT = exports.EVENT_FORM_READY = undefined;
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _from = require('babel-runtime/core-js/array/from');
var _from2 = _interopRequireDefault(_from);
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _promise = require('babel-runtime/core-js/promise');
var _promise2 = _interopRequireDefault(_promise);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _get2 = require('babel-runtime/helpers/get');
var _get3 = _interopRequireDefault(_get2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _Tooltip = require('./Tooltip');
var _Tooltip2 = _interopRequireDefault(_Tooltip);
require('isomorphic-fetch');
var _Event = require('./util/Event');
var _Event2 = _interopRequireDefault(_Event);
var _Util = require('./util/Util');
var _Util2 = _interopRequireDefault(_Util);
var _Settings = require('./util/Settings');
var _Settings2 = _interopRequireDefault(_Settings);
var _DestroyableWidget2 = require('./DestroyableWidget');
var _DestroyableWidget3 = _interopRequireDefault(_DestroyableWidget2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* global HTMLFormElement, fetch, FormData, clearTimeout, NodeList */
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 David Heidrich, BowlingX <me@bowlingx.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*!
* FlexCss.Form
* Licensed under the MIT License (MIT)
* Copyright (c) 2015 David Heidrich, BowlingX <me@bowlingx.com>
*/
var LOADING_CLASS = 'loading';
var DATA_ELEMENT_INVALID = 'data-flexcss-invalid';
var REMOTE = 'data-remote';
var REMOTE_ACTION = 'data-remote-action';
var ATTR_DISABLE_INLINE = 'data-disable-inline-validation';
var ATTR_DISABLE_REALTIME = 'data-disable-realtime-validation';
var ATTR_VALIDATOR = 'data-validate';
var ATTR_DATA_CUSTOM_MESSAGE = 'data-validation-message';
var ATTR_DATA_CUSTOM_LABEL = 'data-custom-label';
var ATTR_VALIDATE_VISIBILITY = 'data-validate-visibility';
var ATTR_ERROR_TARGET_ID = 'data-error-target';
var ATTR_DEPENDS = 'data-depends-selector';
var CONST_USE_JSON = 'json';
var CONST_REALTIME_EVENT = 'input';
var FOCUS_TOOLTIP_DELAY = 20;
var CLICK_TOOLTIP_DELAY = 150;
/**
* Triggered when form is fully initialized and handlers are binded
* @type {string}
*/
var EVENT_FORM_READY = exports.EVENT_FORM_READY = 'flexcss.form.ready';
/**
* Fires when a form is submitted, cancelable
* @type {string}
*/
var EVENT_FORM_SUBMIT = exports.EVENT_FORM_SUBMIT = 'flexcss.form.submit';
/**
* Fired directly after the form has been submitted via ajax
* @type {string}
*/
var EVENT_FORM_AFTER_AJAX_SUBMIT = exports.EVENT_FORM_AFTER_AJAX_SUBMIT = 'flexcss.form.afterAjaxSubmit';
/**
* Fired when ajax events did complete
* @type {string}
*/
var EVENT_FORM_AJAX_COMPLETED = exports.EVENT_FORM_AJAX_COMPLETED = 'flexcss.form.ajaxCompleted';
/**
* A HTML5 Form Validation replacement
*/
var Form = function (_DestroyableWidget) {
(0, _inherits3.default)(Form, _DestroyableWidget);
/**
* @param {HTMLElement} form
* @param [options] optional options
*/
function Form(form, options) {
(0, _classCallCheck3.default)(this, Form);
var _this = (0, _possibleConstructorReturn3.default)(this, (Form.__proto__ || (0, _getPrototypeOf2.default)(Form)).call(this));
Iif (!(form instanceof HTMLFormElement)) {
throw new Error('argument {0} form needs to be an form element');
}
/**
* The Form
* @type {HTMLElement}
*/
_this.form = form;
/**
* @type {Tooltip}
*/
_this.tooltips = null;
/**
* @type {Promise}
*/
_this.currentValidationFuture = new _promise2.default(function () {});
/**
* Default options
* @type {Object}
*/
_this.options = {
// if true creates tooltips above element, uses FlexCss Tooltips
createTooltips: true,
// if true appends error message after input element
appendError: false,
// type of ajax submit
ajaxSubmitType: 'POST',
// json content type if ajax method is set to json
ajaxJsonContentType: 'application/json; charset=utf-8',
// allow inline validation
inlineValidation: true,
// validate in realtime (on `input` event)
realtime: true,
// timeout when realtime event should be captured
realtimeTimeout: 250,
// formatting method for an error
formatErrorTooltip: function formatErrorTooltip(error) {
return '<i class="icon-attention"></i> ' + error;
},
// the class that will be put on the element to mark it failed validation
inputErrorClass: 'invalid',
// the container class for error messages below an element
containerErrorClass: 'form-error',
// additional options for fetch
fetchOptions: {
credentials: 'include'
},
// the container for tooltips
tooltipContainer: form,
tooltipOptions: {
containerClass: 'error-tooltip'
},
shouldScrollToElement: true,
// if you have a fixed header, either set a number or function here
scrollToElementDiff: 0
};
// overwrite default options
(0, _assign2.default)(_this.options, options);
// apply settings from attributes
_Util2.default.applyOptionsFromElement(form, _this.options);
// set form class as widget
// Forms are very different to classical widgets,
// we will not use our base widget class for this but just self
form.hfWidgetInstance = _this;
/**
* A List of Validators
* @type {Object}
* @private
*/
_this._validators = Form.globalValidators;
/**
* @type {Function}
* @private
*/
_this._remoteValidationFunction = null;
_this.initFormValidation();
return _this;
}
(0, _createClass3.default)(Form, [{
key: 'destroy',
value: function destroy() {
(0, _get3.default)(Form.prototype.__proto__ || (0, _getPrototypeOf2.default)(Form.prototype), 'destroy', this).call(this);
if (this.tooltips) {
this.tooltips.destroy();
}
}
/**
* Submits this form, either via ajax or just classical (default)
* @param {HTMLFormElement} thisForm
* @param {Event} e
* @private
* @returns {Promise|boolean} returns false if submit is cancled
*/
}, {
key: '_submitFunction',
value: function _submitFunction(thisForm, e) {
var self = this;
var shouldUseAjax = thisForm.getAttribute(REMOTE);
var ajaxPostUrl = thisForm.getAttribute(REMOTE_ACTION) || thisForm.getAttribute('action') || window.location.href;
var useJson = CONST_USE_JSON === shouldUseAjax;
var ev = _Event2.default.dispatch(thisForm, EVENT_FORM_SUBMIT).withOriginal(e).fire();
// abort execution is event was prevented
if (ev.defaultPrevented) {
self._formStopLoading();
return false;
}
Iif (shouldUseAjax === null) {
// submit
return thisForm.submit();
}
// prevent form from submit normally
e.preventDefault();
// add information that this is an XMLHttpRequest request (used by some frameworks)
var defaultHeaders = {
'X-Requested-With': 'XMLHttpRequest'
};
// setup default headers
Eif (useJson) {
(0, _assign2.default)(defaultHeaders, {
'Content-Type': this.options.ajaxJsonContentType
});
}
var defaultOptions = (0, _assign2.default)(this.options.fetchOptions, {
headers: defaultHeaders,
method: this.options.ajaxSubmitType
});
// support either JSON request payload or normal payload submission
var serverCall = useJson ? fetch(ajaxPostUrl, (0, _assign2.default)(defaultOptions, {
body: (0, _stringify2.default)(this.serialize())
})) : fetch(ajaxPostUrl, (0, _assign2.default)(defaultOptions, {
body: new FormData(thisForm)
}));
_Event2.default.dispatch(thisForm, EVENT_FORM_AFTER_AJAX_SUBMIT).withOriginal(e).fire();
return serverCall.then(function (r) {
(self._remoteValidationFunction || Form.globalRemoteValidationFunction).apply(self, [r]);
_Event2.default.dispatch(thisForm, EVENT_FORM_AJAX_COMPLETED).withOriginal(e).withDetail({ response: r }).fire();
// always remove error class
self._formStopLoading();
});
}
/**
* Serializes a form to a json object
* @returns {Object}
*/
}, {
key: 'serialize',
value: function serialize() {
var selectors = ['input[name]:not([type="radio"]):enabled', 'input[type="radio"][name]:checked', 'select[name]:enabled', 'textarea[name]:enabled'];
var inputs = this.form.querySelectorAll(selectors.join(','));
var result = {};
Array.prototype.forEach.call(inputs, function (input) {
var exists = result[input.name];
var value = input.value;
if (exists instanceof Array) {
exists.push(value);
} else if (exists) {
result[input.name] = [result[input.name], value];
} else {
result[input.name] = value;
}
});
return result;
}
/**
* Handles the chain of validation on given fields
*
* @param {HTMLElement|Array|NodeList} field
* @param [focus] optional focus first error
* @returns {Promise}
*/
}, {
key: 'handleValidation',
value: function handleValidation(field, focus) {
var _this2 = this;
var fields = field instanceof Array || field instanceof NodeList ? field : [field];
return this._handleValidation(fields, focus, true).then(function (r) {
if (!r.foundAnyError) {
// remove tooltips
if (_this2.tooltips) {
_this2.tooltips.removeTooltip();
}
}
return r;
});
}
/**
* Handles errors on given node list
* @param {NodeList} toValidateFields
* @param {boolean} focus
* @param {boolean} scoped if true, will only validate the fields `invalidFields`
* @returns {Promise}
* @private
*/
}, {
key: '_handleValidation',
value: function _handleValidation(toValidateFields, focus, scoped) {
var self = this;
var arr = Form._createArrayFromInvalidFieldList(toValidateFields);
var isLocalInvalid = arr.length > 0;
// focus must appear in the same frame for iOS devices
Eif (isLocalInvalid && focus) {
self._focusElement(arr[0]);
}
var validation = scoped ? this._customValidationsForElements(toValidateFields) : self.validateCustomFields();
return validation.then(function (r) {
Eif (isLocalInvalid) {
// combine browser and custom validators
r.foundAnyError = true;
}
// get a unique field list of all fields that need to be checked and rendered
// it's possible that we have duplicates in non scoped mode
var thisToValidateFields = scoped ? toValidateFields : (0, _from2.default)(arr).concat(r.checkedFields);
r.checkedFields = thisToValidateFields;
var foundInvalidFields = self.prepareErrors(thisToValidateFields, false);
var firstInvalidField = foundInvalidFields[0];
Eif (firstInvalidField) {
Eif (focus) {
self._focusElement(firstInvalidField);
// if element could not be focused:
Eif (document.activeElement !== firstInvalidField) {
self._handleTooltipHideClickAfterChange();
}
} else {
self._handleTooltipHideClickAfterChange();
}
self.showAndOrCreateTooltip(firstInvalidField);
}
return r;
});
}
/**
* @param {HTMLElement} field
* @param {ValidityState} validity
* @returns {*}
* @private
*/
}, {
key: '_setupErrorMessages',
value: function _setupErrorMessages(field, validity) {
return Form.globalErrorMessageHandler ? Form.globalErrorMessageHandler.apply(this, [field, validity]) : false;
}
/**
* Handles class labels for elements
* @param {Object} fields
* @private
*/
}, {
key: '_handleLabels',
value: function _handleLabels(fields) {
var _this3 = this;
(0, _keys2.default)(fields).forEach(function (id) {
var labels = _this3.getForm().querySelectorAll('[for="' + id + '"]');
var invalid = fields[id];
if (labels.length) {
for (var labelsIndex = 0; labelsIndex < labels.length; labelsIndex++) {
var labelEl = labels[labelsIndex];
// we can't use toggle attribute, not supported in IE
if (invalid) {
_this3._markElementInvalid(labelEl);
} else {
_this3._markElementValid(labelEl);
}
}
}
});
}
/**
* @param el
* @private
*/
}, {
key: '_markElementInvalid',
value: function _markElementInvalid(el) {
el.setAttribute(DATA_ELEMENT_INVALID, "true");
el.classList.add(this.options.inputErrorClass);
}
/**
* @param el
* @private
*/
}, {
key: '_markElementValid',
value: function _markElementValid(el) {
el.removeAttribute(DATA_ELEMENT_INVALID);
el.classList.remove(this.options.inputErrorClass);
}
/**
* A List of invalid elements (:invalid)
* @returns {Array}
* @private
*/
}, {
key: '_getInvalidElements',
value: function _getInvalidElements() {
return Array.prototype.filter.call(this.getForm().querySelectorAll(":invalid"), function (r) {
return !(r instanceof HTMLFieldSetElement);
});
}
/**
* @param {HTMLElement} thisParent
* @private
*/
}, {
key: '_removeElementErrors',
value: function _removeElementErrors(thisParent) {
var errors = thisParent.querySelectorAll('.' + this.options.containerErrorClass);
var inputsWithErrorClasses = thisParent.querySelectorAll('[' + DATA_ELEMENT_INVALID + ']');
for (var elementErrorIndex = 0; elementErrorIndex < errors.length; elementErrorIndex++) {
errors[elementErrorIndex].parentNode.removeChild(errors[elementErrorIndex]);
}
for (var inputErrorIndex = 0; inputErrorIndex < inputsWithErrorClasses.length; inputErrorIndex++) {
var el = inputsWithErrorClasses[inputErrorIndex];
this._markElementValid(el);
}
}
/**
* Registers a custom validator
* @param {String} name
* @param {Function} validator a validation function should always return either a Future(true) or Future(false)
* even when the field has been invalidated with `setCustomValidity`, because of different browser `bugs`
* we can't rely on that
* @returns {Form}
*/
}, {
key: 'registerValidator',
value: function registerValidator(name, validator) {
this._validators[name] = validator;
return this;
}
/**
* Runs async validation
* @param {String} validationRef
* @param {HTMLElement} field
* @returns {Promise}
* @private
*/
}, {
key: '_runValidation',
value: function _runValidation(validationRef, field) {
Iif (!this._validators[validationRef]) {
throw new Error('Could not found validator: ' + validationRef);
}
var cl = field.classList;
var future = this._validators[validationRef].apply(this, [field, this.form]);
cl.add(LOADING_CLASS);
future.then(function () {
cl.remove(LOADING_CLASS);
});
return future;
}
/**
* Run custom validations for elements, validations are done async do support XHR Requests or other stuff
*
* @param {Array|NodeList} fields
* @returns {Promise} contains either true if validations passed or false if something went wrong
* @private
*/
}, {
key: '_customValidationsForElements',
value: function _customValidationsForElements(fields) {
var futures = [];
var fieldsLength = fields.length;
var checkedFields = [];
for (var iVal = 0; iVal < fieldsLength; iVal++) {
var field = fields[iVal];
var validationRef = field.getAttribute(ATTR_VALIDATOR);
var validity = field.validity;
Eif (this._validators[validationRef]) {
// use local validation first and then continue with custom validations
Iif (Form._shouldNotValidateField(field) || validity && !validity.customError && !validity.valid) {
continue;
}
checkedFields.push(field);
futures.push(this._runValidation(validationRef, field));
} else {
if (validationRef) {
// console.warn('data-validate was set but no validator was found');
}
}
}
return _promise2.default.all(futures).then(function (allFutures) {
var l = allFutures.length;
var result = {
checkedFields: checkedFields,
foundAnyError: false
};
for (var fI = 0; fI < l; fI++) {
Iif (!allFutures[fI]) {
result.foundAnyError = true;
break;
}
}
return result;
});
}
/**
* Remove all errors for this form
* @returns {Form}
*/
}, {
key: 'removeErrors',
value: function removeErrors() {
this._removeElementErrors(this.form);
Iif (this.tooltips) {
this.tooltips.removeTooltip();
}
return this;
}
/**
* Will handle errors for given fields
* @param {Array|NodeList} fields
* @param {Boolean} removeAllErrors
*/
}, {
key: 'prepareErrors',
value: function prepareErrors(fields, removeAllErrors) {
var _this4 = this;
Iif (removeAllErrors) {
this.removeErrors();
}
var labelGroups = {};
var invalidFields = [];
function handleAdditionalLabels(isInvalid, thisLabelGroup, field) {
var additionalLabels = field.getAttribute(ATTR_DATA_CUSTOM_LABEL) || field.id;
var group = thisLabelGroup[additionalLabels];
Iif (additionalLabels) {
// check additionally if field is currently marked as invalid
// so the label is not marked as error if no field is marked as one
group = group || isInvalid;
thisLabelGroup[additionalLabels] = group;
}
}
// We save all validations in an extra property because we need to reset the validity due some
// implementation errors in other browsers then chrome
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
var errorTarget = Form._findErrorTarget(field);
var parent = errorTarget.parentNode;
var validity = field.validity;
var isInvalid = validity && !validity.valid;
Iif (Form._shouldNotValidateField(field)) {
continue;
}
field.flexFormsSavedValidity = JSON.parse((0, _stringify2.default)(validity));
handleAdditionalLabels(isInvalid, labelGroups, field);
Eif (isInvalid) {
Eif (!removeAllErrors) {
// Remove current errors:
this._removeElementErrors(parent);
}
// setup custom error messages:
this._setupErrorMessages(field, validity);
var msg = field.validationMessage;
// mark fields as invalid
this._markElementInvalid(errorTarget);
this._markElementInvalid(field);
Iif (this.options.appendError) {
parent.insertAdjacentHTML("beforeend", '<div class="' + this.options.containerErrorClass + '">' + msg + '</div>');
}
invalidFields.push(field);
field.flexFormsSavedValidationMessage = msg;
} else {
// restore invalid fields
this._markElementValid(errorTarget);
this._markElementValid(field);
// cleanup
delete field.flexFormsSavedValidationMessage;
// remove error markup
this._removeElementErrors(parent);
}
// We have to reset the custom validity here to allow native validations work again
field.setCustomValidity('');
}
// if validates a single field we need to check the linked fields to a label:
if (fields.length === 1) {
var _field = fields[0];
var id = _field.getAttribute(ATTR_DATA_CUSTOM_LABEL) || _field.id;
Iif (id) {
var linkedFields = (0, _from2.default)(this.getForm().querySelectorAll('[' + ATTR_DATA_CUSTOM_LABEL + '="' + id + '"], #' + id));
linkedFields.forEach(function (thisField) {
var validity = thisField.validity;
var isInvalid = validity && !validity.valid && _this4._isElementInvalidElement(thisField);
handleAdditionalLabels(isInvalid, labelGroups, thisField);
});
}
}
this._handleLabels(labelGroups);
return invalidFields;
}
/**
* Validates all custom fields
* @returns {Promise}
*/
}, {
key: 'validateCustomFields',
value: function validateCustomFields() {
return this._customValidationsForElements(this.form.querySelectorAll("[data-validate]"));
}
/**
* Tests if a field should be validated
* @param {HTMLElement} field
* @returns {boolean}
* @private
*/
}, {
key: 'getForm',
/**
* This form
* @returns {HTMLElement}
*/
value: function getForm() {
return this.form;
}
/**
* Registers a function that handles remote validation
* @param {Function} func
* @returns {Form}
*/
}, {
key: 'registerRemoteValidation',
value: function registerRemoteValidation(func) {
this._remoteValidationFunction = func;
return this;
}
/**
* Formats the error content for the tooltip
* @param {String} error
* @returns {String}
* @private
*/
}, {
key: '_formatErrorTooltip',
value: function _formatErrorTooltip(error) {
return this.options.formatErrorTooltip.apply(this, [error]);
}
/**
* Tries to find a custom error target on given target
* @param target
* @returns {HTMLElement}
* @private
*/
}, {
key: 'showAndOrCreateTooltip',
/**
* Creates a tooltip at given element, will only create a new instance if not created
* @param {HTMLElement} target
* @param {Boolean} [remove]
*/
value: function showAndOrCreateTooltip(target, remove) {
var self = this;
Eif (!this.tooltips && this.options.createTooltips) {
this.tooltips = new _Tooltip2.default(this.options.tooltipContainer, this.options.tooltipOptions);
}
Iif (!this.options.createTooltips) {
return false;
}
Iif (!target.flexFormsSavedValidity) {
return false;
}
var errorTarget = Form._findErrorTarget(target);
var result = false;
Eif (!target.flexFormsSavedValidity.valid && self._isElementInvalidElement(errorTarget)) {
self.tooltips.createTooltip(errorTarget, self._formatErrorTooltip(target.flexFormsSavedValidationMessage), false);
result = true;
} else {
if (remove) {
self.tooltips.removeTooltip();
}
}
return result;
}
/**
* Checks if element is marked as invalid
* @param {HTMLElement} el
* @returns {boolean}
* @private
*/
}, {
key: '_isElementInvalidElement',
value: function _isElementInvalidElement(el) {
return el.hasAttribute(DATA_ELEMENT_INVALID);
}
/**
* Handles invalid event of a form
* @param {Event} e
* @returns {Promise|boolean}
* @private
*/
}, {
key: '_checkIsInvalid',
value: function _checkIsInvalid(e) {
e.preventDefault();
var invalidFields = this.getForm().querySelectorAll(":invalid");
return this._handleValidation(invalidFields, true, false);
}
/**
* Will query dependent fields (by selector) that should be validated with given field
* @param field
* @returns {NodeList|[]}
* @private
*/
}, {
key: '_getDependentFields',
value: function _getDependentFields(field) {
var fieldSelector = field.getAttribute(ATTR_DEPENDS);
var base = [field];
if (fieldSelector) {
base.push.apply(base, Array.prototype.slice.apply(this.getForm().querySelectorAll(fieldSelector)));
}
return base;
}
/**
* @private
* @param {HTMLElement} [target]
*/
}, {
key: '_handleTooltipInline',
value: function _handleTooltipInline(target) {
Iif (this.tooltips) {
this.tooltips.removeTooltip(target);
}
}
/**
* Initializes validation for a given form, registers event handlers
*/
}, {
key: 'initFormValidation',
value: function initFormValidation() {
var _this5 = this;
// Suppress the default bubbles
var self = this;
var form = this.getForm();
var invalidEvent = 'invalid';
/**
* Validates if is valid realtime element
* @param {HTMLElement} target
* @returns {boolean}
* @private
*/
function _checkIsValidRealtimeElement(target) {
return !target.hasAttribute(ATTR_DISABLE_REALTIME) && !target.hasAttribute(ATTR_DISABLE_INLINE);
}
form.addEventListener(invalidEvent, function (e) {
e.preventDefault();
}, true);
_Util2.default.addEventOnce(invalidEvent, form, function handleInvalid(e) {
self._formLoading();
var result = self._checkIsInvalid(e);
Eif (result) {
self.currentValidationFuture = new _promise2.default(function (resolve) {
result.then(function (r) {
setTimeout(function () {
_Util2.default.addEventOnce(invalidEvent, form, handleInvalid, true);
}, 0);
resolve(r);
self._formStopLoading();
Iif (!r.foundAnyError) {
self._formLoading();
self._handleSubmit(e);
}
});
});
}
}, true);
this.addEventListener(form, 'reset', function () {
_this5.removeErrors();
});
// Timeout for keys:
var TIMEOUT_KEYDOWN = void 0;
var KEYDOWN_RUNNING = false;
// resets keydown events
function clearKeyDownTimeout() {
KEYDOWN_RUNNING = false;
clearTimeout(TIMEOUT_KEYDOWN);
}
// setup custom realtime event if given
Eif (self.options.realtime) {
this.addEventListener(form, CONST_REALTIME_EVENT, function (e) {
if (self._formIsLoading()) {
return;
}
var target = e.target;
clearTimeout(TIMEOUT_KEYDOWN);
if (KEYDOWN_RUNNING) {
return;
}
TIMEOUT_KEYDOWN = setTimeout(function () {
var isStillTarget = document.activeElement === e.target;
if (!_checkIsValidRealtimeElement(target)) {
return;
}
if (isStillTarget) {
self._handleTooltipInline();
}
KEYDOWN_RUNNING = true;
var dependentFields = self._getDependentFields(target);
self._customValidationsForElements(dependentFields).then(function () {
self.prepareErrors(dependentFields, false);
if (isStillTarget) {
self.showAndOrCreateTooltip(e.target);
}
// future must be resolved before another event can be started
KEYDOWN_RUNNING = false;
});
}, self.options.realtimeTimeout);
}, true);
}
/**
* Validates if target is a valid input field to check blur and focus events
*
* @param {HTMLElement} target
* @returns {boolean}
* @private
*/
function _checkIsValidBlurFocusElement(target) {
var attr = target.getAttribute("type");
return attr !== "radio" && attr !== "checkbox" && attr !== "submit";
}
/**
* Validates if is valid inline-check element
* @param {HTMLElement} target
* @returns {boolean}
* @private
*/
function _checkIsValidInlineCheckElement(target) {
return !target.hasAttribute(ATTR_DISABLE_INLINE);
}
this.addEventListener(form, 'blur', function (e) {
// do not hide tooltip after change event
Eif (!e.target.flexcssKeepTooltips) {
self._handleTooltipInline(e.target);
}
delete e.target.flexcssKeepTooltips;
}, true);
// handle focus on input elements
// will show an error if field is invalid
this.addEventListener(form, "focus", function (e) {
Eif (self._formIsLoading()) {
return;
}
// do not track errors for checkbox and radios on focus:
if (!_checkIsValidBlurFocusElement(e.target)) {
return;
}
// we need to delay this a little, because Firefox and Safari do not show a tooltip after it
// just have been hidden (on blur). Maybe fix this with a queue later
setTimeout(function () {
self.showAndOrCreateTooltip(e.target);
}, FOCUS_TOOLTIP_DELAY);
}, true);
Eif (self.options.inlineValidation) {
// Handle change for checkbox, radios and selects
this.addEventListener(form, "change", function (e) {
var target = e.target;
if (self._formIsLoading() || !_checkIsValidInlineCheckElement(target)) {
return;
}
clearKeyDownTimeout();
var name = target.getAttribute('name');
var inputs = name ? form.querySelectorAll('[name="' + name + '"]') : [target];
// we only support dependent fields for a single widgets right now
if (inputs.length === 1) {
inputs = self._getDependentFields(target);
}
self._customValidationsForElements(inputs).then(function () {
self.prepareErrors(inputs, false);
target.flexcssKeepTooltips = self.showAndOrCreateTooltip(target, true);
if (target.flexcssKeepTooltips) {
self._handleTooltipHideClickAfterChange();
}
});
});
}
// prevent default if form is invalid
this.addEventListener(form, "submit", function listener(e) {
self._submitListener(e, listener);
});
_Event2.default.dispatchAndFire(form, EVENT_FORM_READY);
}
/* Loading states, unfortunately we can't check if a promise is pending :/*/
/* TODO: Maybe wrap promise to extend this functionality */
}, {
key: '_formLoading',
value: function _formLoading() {
this.getForm().classList.add(LOADING_CLASS);
}
}, {
key: '_formStopLoading',
value: function _formStopLoading() {
this.getForm().classList.remove(LOADING_CLASS);
}
}, {
key: '_formIsLoading',
value: function _formIsLoading() {
return this.getForm().classList.contains(LOADING_CLASS);
}
// this defines the logic after a change event when a tooltip is shown
// because we call this method inside the change event, the click would be immeditally executed with the change
// event when not using setTimeout(). There might be another solution for this...
}, {
key: '_handleTooltipHideClickAfterChange',
value: function _handleTooltipHideClickAfterChange() {
var self = this;
Eif (this.options.createTooltips) {
setTimeout(function () {
_Util2.default.addEventOnce(_Settings2.default.getTabEvent(), global.document.body, function (t) {
if (!self._isElementInvalidElement(t.target)) {
self._handleTooltipInline();
}
});
}, CLICK_TOOLTIP_DELAY);
}
}
}, {
key: '_focusElement',
value: function _focusElement(el) {
el.focus();
Eif (this.options.shouldScrollToElement) {
_Util2.default.scrollToElement(el, this.options.scrollToElementDiff);
}
}
/**
* Listener that is executed on form submit
* @param e
* @param submitListener
* @returns {boolean}
* @private
*/
}, {
key: '_submitListener',
value: function _submitListener(e, submitListener) {
var form = this.getForm();
var self = this;
var submitEvent = 'submit';
Iif (this._formIsLoading()) {
e.preventDefault();
return false;
}
this._formLoading();
form.removeEventListener(submitEvent, submitListener);
this.removeErrors();
e.preventDefault();
// reset:
Eif (form.checkValidity()) {
form.addEventListener(submitEvent, submitListener);
// It's possible that the form is valid but the custom validations need to be checked again:
self.currentValidationFuture = new _promise2.default(function (resolve) {
var validation = self.validateCustomFields();
validation.then(function (r) {
// because custom validators may mark multiple fields as invalid, we get all of them in the form
var fields = self._getInvalidElements();
var errors = self.prepareErrors(fields, false);
var firstError = errors[0];
Iif (firstError) {
self._focusElement(firstError);
self.showAndOrCreateTooltip(firstError, true);
}
resolve(r);
});
});
self.currentValidationFuture.then(function (r) {
Eif (!r.foundAnyError) {
// Handle submitting the form to server:
self._handleSubmit(e);
} else {
self._formStopLoading();
}
});
} else {
self._formStopLoading();
form.addEventListener(submitEvent, submitListener);
}
}
/**
* Handles submitting, optionally allows to stop submitting
* @param e
* @private
*/
}, {
key: '_handleSubmit',
value: function _handleSubmit(e) {
this._submitFunction(this.form, e);
}
/**
* Registers a global event Handler
* @param errorFunc
*/
}], [{
key: '_shouldNotValidateField',
value: function _shouldNotValidateField(field) {
var target = Form._findErrorTarget(field);
return target instanceof HTMLFieldSetElement || field.validity === undefined || target.hasAttribute(ATTR_VALIDATE_VISIBILITY) && !_Util2.default.isVisible(target);
}
/**
* Creates an array from a node list with invalid items
* This Method expicitly checks if field should not be validated so it can be used to foucs a field
* @param list
* @returns {Array}
* @private
*/
}, {
key: '_createArrayFromInvalidFieldList',
value: function _createArrayFromInvalidFieldList(list) {
var arr = [];
for (var i = 0; i < list.length; ++i) {
var n = list[i];
Eif (n.validity && !n.validity.valid) {
Eif (!Form._shouldNotValidateField(n)) {
arr.push(n);
}
}
}
return arr;
}
}, {
key: '_findErrorTarget',
value: function _findErrorTarget(target) {
var el = target.getAttribute(ATTR_ERROR_TARGET_ID) || target;
var foundTarget = el instanceof HTMLElement ? el : global.document.getElementById(el);
Iif (!foundTarget) {
throw new Error('Given error target did not exists: ' + target);
}
return foundTarget;
}
}, {
key: 'registerErrorMessageHandler',
value: function registerErrorMessageHandler(errorFunc) {
Form.globalErrorMessageHandler = errorFunc;
}
/**
* Initialize forms for a specific selector
* @param {String} selector
* @param {Object} [options]
* @return {array.<Form>}
*/
}, {
key: 'init',
value: function init(selector, options) {
var forms = selector instanceof HTMLElement ? selector.querySelectorAll('form') : document.querySelectorAll(selector);
var instances = [];
for (var i = 0; i < forms.length; i++) {
instances.push(new Form(forms[i], options));
}
return instances;
}
/**
* Registers a global validator that is usable on all form instances
* @param {String} name
* @param {Function} validator
* @returns {Function}
*/
}, {
key: 'registerValidator',
value: function registerValidator(name, validator) {
Form.globalValidators[name] = validator;
return Form;
}
/**
* Registers a global function that is called when a form should validate the response of a server
* @param {Function} func
* @returns {Form}
*/
}, {
key: 'registerGlobalRemoteValidationFunction',
value: function registerGlobalRemoteValidationFunction(func) {
Form.globalRemoteValidationFunction = func;
return Form;
}
}]);
return Form;
}(_DestroyableWidget3.default);
/**
* Global validators
* @type {Array}
*/
Form.globalValidators = [];
/**
* Global Remote validation function
*/
Form.globalRemoteValidationFunction = function () {};
/**
* Handles custom error messages extracts custom message by default
*/
Form.globalErrorMessageHandler = function (field, validity) {
Eif (!validity.customError) {
var customMsg = field.getAttribute(ATTR_DATA_CUSTOM_MESSAGE);
Iif (customMsg) {
field.setCustomValidity(customMsg);
}
}
};
exports.default = Form;
|