forked from Jakobovski/angular-validator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular-validator.js
More file actions
249 lines (197 loc) · 11.2 KB
/
angular-validator.js
File metadata and controls
249 lines (197 loc) · 11.2 KB
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
angular.module('angularValidator', []);
angular.module('angularValidator').directive('angularValidator',
function() {
return {
restrict: 'A',
link: function(scope, element, attrs, fn) {
// This is the DOM form element
var DOMForm = angular.element(element)[0];
// This is the the scope form model
// All validation states are contained here
var form_name = DOMForm.attributes['name'].value;
var scopeForm = scope[form_name];
// Set the default submitted state to false
scopeForm.submitted = false;
// Watch form length to add watches for new form elements
scope.$watch(function(){return DOMForm.length;}, function(){
setupWatches(DOMForm);
});
// Intercept and handle submit events of the form
element.on('submit', function(event) {
event.preventDefault();
scope.$apply(function() {
scopeForm.submitted = true;
});
// If the form is valid then call the function that is declared in the angular-validator-submit atrribute on the form element
if (scopeForm.$valid) {
scope.$apply(function() {
scope.$eval(DOMForm.attributes["angular-validator-submit"].value);
});
}
});
scopeForm.reset = function(){
// Clear all the form values
for (var i = 0; i < DOMForm.length; i++) {
if (DOMForm[i].name){
scopeForm[DOMForm[i].name].$setViewValue("");
scopeForm[DOMForm[i].name].$render();
}
}
scopeForm.submitted = false;
scopeForm.$setPristine();
};
// Setup watches on all form fields
setupWatches(DOMForm);
// Iterate through the form fields and setup watches on each one
function setupWatches(formElement) {
for (var i = 0; i < formElement.length; i++) {
// This ensures we are only watching form fields
if (i in formElement) {
setupWatch(formElement[i]);
}
}
}
// Setup $watch on a single formfield
function setupWatch(elementToWatch) {
if (elementToWatch.isWatchedByValidator){
return;
}
elementToWatch.isWatchedByValidator = true;
// If element is set to validate on blur then update the element on blur
if ("validate-on" in elementToWatch.attributes && elementToWatch.attributes["validate-on"].value === "blur") {
angular.element(elementToWatch).on('blur', function() {
updateValidationMessage(elementToWatch);
updateValidationClass(elementToWatch);
});
}
scope.$watch(function() {
return elementToWatch.value + elementToWatch.required + scopeForm.submitted + checkElementValidity(elementToWatch) + getDirtyValue(scopeForm[elementToWatch.name]) + getValidValue(scopeForm[elementToWatch.name]);
},
function() {
if (scopeForm.submitted){
updateValidationMessage(elementToWatch);
updateValidationClass(elementToWatch);
}
else {
// Determine if the element in question is to be updated on blur
isDirtyElement = "validate-on" in elementToWatch.attributes && elementToWatch.attributes["validate-on"].value === "dirty";
if (isDirtyElement){
updateValidationMessage(elementToWatch);
updateValidationClass(elementToWatch);
}
// This will get called in the case of resetting the form. This only gets called for elements that update on blur and submit.
else if (scopeForm[elementToWatch.name] && scopeForm[elementToWatch.name].$pristine){
updateValidationMessage(elementToWatch);
updateValidationClass(elementToWatch);
}
}
});
}
// Returns the $dirty value of the element if it exists
function getDirtyValue(element) {
if (element) {
if ("$dirty" in element) {
return element.$dirty;
}
}
}
function getValidValue(element) {
if (element) {
if ("$valid" in element) {
return element.$valid;
}
}
}
function checkElementValidity(element) {
// If element has a custom validation function
if ("validator" in element.attributes) {
// Call the custom validator function
var isElementValid = scope.$eval(element.attributes.validator.value);
scopeForm[element.name].$setValidity("angularValidator", isElementValid);
return isElementValid;
}
}
// Adds and removes an error message as a sibling element of the form field
// depending on the validity of the form field and the submitted state of the form.
// Will use default message if a custom message is not given
function updateValidationMessage(element) {
var defaultRequiredMessage = function() {
return "<i class='fa fa-times'></i> Required";
};
var defaultInvalidMessage = function() {
return "<i class='fa fa-times'></i> Invalid";
};
// Make sure the element is a form field and not a button for example
// Only form elements should have names.
if (!(element.name in scopeForm)) {
return;
}
var scopeElementModel = scopeForm[element.name];
// Remove all validation messages
var validationMessageElement = isValidationMessagePresent(element);
if (validationMessageElement) {
validationMessageElement.remove();
}
// Only add validation messages if the form field is $dirty or the form has been submitted
if (scopeElementModel.$dirty || scope[element.form.name].submitted) {
if (scopeElementModel.$error.required) {
// If there is a custom required message display it
if ("required-message" in element.attributes) {
angular.element(element).after(generateErrorMessage(element.attributes['required-message'].value));
}
// Display the default required message
else {
angular.element(element).after(generateErrorMessage(defaultRequiredMessage));
}
} else if (!scopeElementModel.$valid) {
// If there is a custom validation message add it
if ("invalid-message" in element.attributes) {
angular.element(element).after(generateErrorMessage(element.attributes['invalid-message'].value));
}
// Display the default error message
else {
angular.element(element).after(generateErrorMessage(defaultInvalidMessage));
}
}
}
}
function generateErrorMessage(messageText) {
return "<label class='control-label has-error validationMessage'>" + scope.$eval(messageText) + "</label>";
}
// Returns the validation message element or False
function isValidationMessagePresent(element) {
var elementSiblings = angular.element(element).parent().children();
for (var i = 0; i < elementSiblings.length; i++) {
if (angular.element(elementSiblings[i]).hasClass("validationMessage")) {
return angular.element(elementSiblings[i]);
}
}
return false;
}
// Adds and removes .has-error class to both the form element and the form element's parent
// depending on the validity of the element and the submitted state of the form
function updateValidationClass(element) {
// Make sure the element is a form field and not a button for example
// Only form fields should have names.
if (!(element.name in scopeForm)) {
return;
}
var formField = scopeForm[element.name];
// This is extra for users wishing to implement the .has-error class on the field itself
// instead of on the parent element. Note that Bootstrap requires the .has-error class to be on the parent element
angular.element(element).removeClass('has-error');
angular.element(element.parentNode).removeClass('has-error');
// Only add/remove validation classes if the field is $dirty or the form has been submitted
if (formField.$dirty || scope[element.form.name].submitted) {
if (formField.$invalid) {
angular.element(element.parentNode).addClass('has-error');
// This is extra for users wishing to implement the .has-error class on the field itself
// instead of on the parent element. Note that Bootstrap requires the .has-error class to be on the parent element
angular.element(element).addClass('has-error');
}
}
}
}
};
}
);