forked from refactorthis/xtform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xtForm.js
320 lines (267 loc) · 11.6 KB
/
xtForm.js
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
/*
xtForm
--------------------------------------------------------------------------
Creates validators and attaches them to inputs
Handles client side validation in tooltips
Allows for custom error message overrides
*/
(function (angular) {
'use strict';
function InputValidator(scope, element, attrs, ngModel, errors) {
var self = this,
prop;
this.errorMessages = errors;
this.scope = scope;
this.element = element;
this.ngModel = ngModel;
this.attrs = attrs;
var observe = function (prop) {
var innerProp = prop;
attrs.$observe(innerProp, function (val) {
self.errorMessages[innerProp.substring(3, innerProp.length).toLowerCase()] = val;
});
};
for (prop in attrs) {
if (attrs.hasOwnProperty(prop) && prop.indexOf('msg') === 0) {
observe(prop);
}
}
this.ngModel.$parsers.unshift(function (value) {
return value === '' ? null : value;
});
// tried viewListeners, parsers, different watches.. seems this is the best
scope.$watch(function () {
return ngModel.$error;
}, function (valid) {
if (ngModel.$dirty) {
self.showErrors();
} else {
self.resetValidity();
}
}, true);
}
InputValidator.prototype.setDirty = function (value) {
this.ngModel.$dirty = value;
this.ngModel.$pristine = !value;
this.element
.toggleClass('ng-dirty', value)
.toggleClass('ng-pristine', !value);
};
InputValidator.prototype.showErrors = function (isSubmit) {
var ngModel = this.ngModel;
this.setDirty(true);
if (!ngModel.$valid) {
// build error summary
var errors = '',
propCount = 0;
// calculated here as it could be variable
var bounds = {
minlength: this.attrs.ngMinlength,
maxlength: this.attrs.ngMaxlength,
min: this.attrs.min,
max: this.attrs.max
};
for (var prop in ngModel.$error) {
var key = prop.toLowerCase();
if (prop != 'required' && ngModel.$error[prop] === true && this.errorMessages[key]) {
propCount++;
var errString = this.errorMessages[key] + '';
for (var bound in bounds) {
errString = errString.replace('{{' + bound + '}}', bounds[bound]);
}
errors += errString + '<br>';
}
}
if (propCount === 0 && ngModel.$error.required === true) {
errors += this.errorMessages.required + '<br>';
}
if (ngModel.$error.messages !== undefined) {
errors += ngModel.$error.messages;
}
this.element.addClass('xt-error');
// allow for a different tooltip element
if (this.attrs.tooltipElement) {
this.element = angular.element(document.getElementById(this.attrs.tooltipElement));
this.element.addClass('xt-error-container');
}
if (this.tooltipSet === true) {
this.element.tooltip('destroy');
}
// create tooltip
this.element.tooltip({
html: true,
title: errors,
placement: this.attrs.placement || 'bottom',
trigger: this.attrs.trigger || 'focus hover',
container: this.attrs.container || 'body'
});
if (this.profile === 'showAll' || !isSubmit) {
this.element.tooltip('show');
}
this.tooltipSet = true;
} else {
this.resetValidity();
}
};
InputValidator.prototype.resetValidity = function () {
var that = this;
setTimeout(function () {
// remove tooltip if needed
if (that.tooltipSet) {
that.ngModel.$error.messages = undefined;
that.element.removeClass('xt-error');
that.element.tooltip('destroy');
that.tooltipSet = false;
that.scope.$apply();
}
});
};
if (!angular.isFunction(angular.element.prototype.tooltip)) {
throw new Error('xtform requires a jquery tooltip plugin, like bootstrap.js');
}
angular.module('xtForm', [])
.provider('xtFormErrors', function () {
var _errors = {
minlength: 'Needs to be at least {{minlength}} characters long',
maxlength: 'Can be no longer than {{maxlength}} characters long',
required: 'This field is required',
number: 'Must be a number',
min: 'Must be at least {{min}}',
max: 'Must be no greater than {{max}}',
email: 'Invalid Email',
pattern: 'Illegal value'
};
this.setErrors = function (errors) {
angular.extend(_errors, errors);
};
this.$get = function () {
return _errors;
};
})
.directive('xtForm', ['$parse', 'xtFormErrors', function ($parse, xtFormErrors) {
return {
require: ['form', 'xtForm'],
controller: [
'$scope',
'$element',
'$attrs',
function ($scope, $element, $attrs) {
// Holds all validators
this.validators = {
_validators: {},
registerValidator: function (name, validator) {
validator.profile = $attrs.profile || 'default';
this._validators[name] = validator;
},
deregisterValidator: function (name) {
this._validators[name].ngModel.$valid = true;
this._validators[name].showErrors();
delete this._validators[name];
},
hasValidator: function (name) {
return this._validators[name] !== undefined;
},
getValidator: function (name) {
return this._validators[name];
},
resetValidity: function () {
angular.forEach(this._validators, function (validator) {
validator.resetValidity(false);
});
},
showAllErrors: function () {
angular.forEach(this._validators, function (validator) {
validator.showErrors(true);
});
}
};
this.$element = $element;
}
],
link: function (scope, element, attrs, ctrl) {
var control = {
onSubmit: function () {
}
},
formCtrl = ctrl[0],
xtFormCtrl = ctrl[1];
function submit() {
formCtrl.$setDirty();
if (!formCtrl.$valid) {
xtFormCtrl.validators.showAllErrors();
control.onSubmit(false);
return;
}
//reset
xtFormCtrl.validators.resetValidity();
control.onSubmit(true);
}
function validate() {
formCtrl.$setDirty();
if (!formCtrl.$valid) {
xtFormCtrl.validators.showAllErrors();
return false;
} else {
return true;
}
}
function reset() {
xtFormCtrl.validators.resetValidity();
}
// add save functionality to the form control
// (i got this style from angular-ui. I kind of think it looks like an antipattern but
// but I can't find a cleaner way of controller/directive comm)
if (attrs.xtForm) {
var temp = scope.$eval(attrs.xtForm);
if (temp !== undefined) {
control = temp;
var that = this;
control.submit = function () {
submit.apply(that, arguments);
};
control.reset = function () {
reset.apply(that, arguments);
};
control.validate = function () {
validate.apply(that, arguments);
};
}
}
// wire up default submit of form to save function
element.on('submit', function (evt) {
submit();
evt.preventDefault();
return false;
});
element.on('$destroy', function () {
xtFormCtrl.$element = null;
xtFormCtrl.validators = null;
});
}
};
}])
.directive('xtValidate', ['xtFormErrors', function (xtFormErrors) {
return {
require: ['ngModel', '^xtForm', '^form'],
priority: 99,
link: function (scope, element, attrs, ctrls) {
var ngModel = ctrls[0],
xtFormCtrl = ctrls[1],
errors = angular.copy(xtFormErrors);
if (ngModel.$name === undefined) {
throw new Error('element must have a "name" attribute to use xtValidate');
}
if (element[0].nodeName.toUpperCase() === 'SELECT' && attrs.placement === undefined) {
attrs.placement = 'top';
}
var validator = new InputValidator(scope, element, attrs, ngModel, errors);
xtFormCtrl.validators.registerValidator(attrs.name, validator);
element.on('$destroy', function () {
if (xtFormCtrl && xtFormCtrl.validators && xtFormCtrl.validators.hasValidator(attrs.name)) {
xtFormCtrl.validators.deregisterValidator(attrs.name);
}
});
}
};
}]);
})(window.angular);