| 5048 |
dpurdie |
1 |
/**
|
|
|
2 |
* jQuery Form Validator
|
|
|
3 |
* ------------------------------------------
|
|
|
4 |
* Created by Victor Jonsson <http://www.victorjonsson.se>
|
|
|
5 |
*
|
|
|
6 |
* @website http://formvalidator.net/
|
|
|
7 |
* @license Dual licensed under the MIT or GPL Version 2 licenses
|
|
|
8 |
* @version 2.2.beta.69
|
|
|
9 |
*/
|
|
|
10 |
(function ($) {
|
|
|
11 |
|
|
|
12 |
'use strict';
|
|
|
13 |
|
|
|
14 |
var $window = $(window),
|
|
|
15 |
_getInputParentContainer = function ($elem) {
|
|
|
16 |
if ($elem.valAttr('error-msg-container')) {
|
|
|
17 |
return $($elem.valAttr('error-msg-container'));
|
|
|
18 |
} else {
|
|
|
19 |
var $parent = $elem.parent();
|
|
|
20 |
if (!$parent.hasClass('form-group')) {
|
|
|
21 |
var $formGroup = $parent.closest('.form-group');
|
|
|
22 |
if ($formGroup.length) {
|
|
|
23 |
return $formGroup.eq(0);
|
|
|
24 |
}
|
|
|
25 |
}
|
|
|
26 |
return $parent;
|
|
|
27 |
}
|
|
|
28 |
},
|
|
|
29 |
_applyErrorStyle = function ($elem, conf) {
|
|
|
30 |
$elem
|
|
|
31 |
.addClass(conf.errorElementClass)
|
|
|
32 |
.removeClass('valid');
|
|
|
33 |
|
|
|
34 |
_getInputParentContainer($elem)
|
|
|
35 |
.addClass(conf.inputParentClassOnError)
|
|
|
36 |
.removeClass(conf.inputParentClassOnSuccess);
|
|
|
37 |
|
|
|
38 |
if (conf.borderColorOnError !== '') {
|
|
|
39 |
$elem.css('border-color', conf.borderColorOnError);
|
|
|
40 |
}
|
|
|
41 |
},
|
|
|
42 |
_removeErrorStyle = function ($elem, conf) {
|
|
|
43 |
$elem.each(function () {
|
|
|
44 |
var $this = $(this);
|
|
|
45 |
|
|
|
46 |
_setInlineErrorMessage($this, '', conf, conf.errorMessagePosition);
|
|
|
47 |
|
|
|
48 |
$this
|
|
|
49 |
.removeClass('valid')
|
|
|
50 |
.removeClass(conf.errorElementClass)
|
|
|
51 |
.css('border-color', '');
|
|
|
52 |
|
|
|
53 |
_getInputParentContainer($this)
|
|
|
54 |
.removeClass(conf.inputParentClassOnError)
|
|
|
55 |
.removeClass(conf.inputParentClassOnSuccess)
|
|
|
56 |
.find('.' + conf.errorMessageClass) // remove inline span holding error message
|
|
|
57 |
.remove();
|
|
|
58 |
});
|
|
|
59 |
},
|
|
|
60 |
_setInlineErrorMessage = function ($input, mess, conf, $messageContainer) {
|
|
|
61 |
var custom = document.getElementById($input.attr('name') + '_err_msg');
|
|
|
62 |
if (custom) {
|
|
|
63 |
custom.innerHTML = mess;
|
|
|
64 |
}
|
|
|
65 |
else if (typeof $messageContainer == 'object') {
|
|
|
66 |
var $found = false;
|
|
|
67 |
$messageContainer.find('.' + conf.errorMessageClass).each(function () {
|
|
|
68 |
if (this.inputReferer == $input[0]) {
|
|
|
69 |
$found = $(this);
|
|
|
70 |
return false;
|
|
|
71 |
}
|
|
|
72 |
});
|
|
|
73 |
if ($found) {
|
|
|
74 |
if (!mess) {
|
|
|
75 |
$found.remove();
|
|
|
76 |
} else {
|
|
|
77 |
$found.html(mess);
|
|
|
78 |
}
|
|
|
79 |
} else {
|
|
|
80 |
var $mess = $('<div class="' + conf.errorMessageClass + '">' + mess + '</div>');
|
|
|
81 |
$mess[0].inputReferer = $input[0];
|
|
|
82 |
$messageContainer.prepend($mess);
|
|
|
83 |
}
|
|
|
84 |
}
|
|
|
85 |
else {
|
|
|
86 |
|
|
|
87 |
var $parent = _getInputParentContainer($input),
|
|
|
88 |
$mess = $parent.find('.' + conf.errorMessageClass + '.help-block');
|
|
|
89 |
|
|
|
90 |
if ($mess.length == 0) {
|
|
|
91 |
$mess = $('<span></span>').addClass('help-block').addClass(conf.errorMessageClass);
|
|
|
92 |
$mess.appendTo($parent);
|
|
|
93 |
}
|
|
|
94 |
$mess.html(mess);
|
|
|
95 |
}
|
|
|
96 |
},
|
|
|
97 |
_templateMessage = function ($form, title, errorMessages, conf) {
|
|
|
98 |
var messages = conf.errorMessageTemplate.messages.replace(/\{errorTitle\}/g, title),
|
|
|
99 |
fields = [],
|
|
|
100 |
container;
|
|
|
101 |
|
|
|
102 |
$.each(errorMessages, function (i, msg) {
|
|
|
103 |
fields.push(conf.errorMessageTemplate.field.replace(/\{msg\}/g, msg));
|
|
|
104 |
});
|
|
|
105 |
|
|
|
106 |
messages = messages.replace(/\{fields\}/g, fields.join(''));
|
|
|
107 |
container = conf.errorMessageTemplate.container.replace(/\{errorMessageClass\}/g, conf.errorMessageClass);
|
|
|
108 |
container = container.replace(/\{messages\}/g, messages);
|
|
|
109 |
$form.children().eq(0).before(container);
|
|
|
110 |
};
|
|
|
111 |
|
|
|
112 |
/**
|
|
|
113 |
* Assigns validateInputOnBlur function to elements blur event
|
|
|
114 |
*
|
|
|
115 |
* @param {Object} language Optional, will override $.formUtils.LANG
|
|
|
116 |
* @param {Object} settings Optional, will override the default settings
|
|
|
117 |
* @return {jQuery}
|
|
|
118 |
*/
|
|
|
119 |
$.fn.validateOnBlur = function (language, settings) {
|
|
|
120 |
this.find('input[data-validation],textarea[data-validation],select[data-validation]')
|
|
|
121 |
.bind('blur.validation', function () {
|
|
|
122 |
$(this).validateInputOnBlur(language, settings, true, 'blur');
|
|
|
123 |
});
|
|
|
124 |
if (settings.validateCheckboxRadioOnClick) {
|
|
|
125 |
// bind click event to validate on click for radio & checkboxes for nice UX
|
|
|
126 |
this.find('input[type=checkbox][data-validation],input[type=radio][data-validation]')
|
|
|
127 |
.bind('click.validation', function () {
|
|
|
128 |
$(this).validateInputOnBlur(language, settings, true, 'click');
|
|
|
129 |
});
|
|
|
130 |
}
|
|
|
131 |
|
|
|
132 |
return this;
|
|
|
133 |
};
|
|
|
134 |
|
|
|
135 |
/*
|
|
|
136 |
* Assigns validateInputOnBlur function to elements custom event
|
|
|
137 |
* @param {Object} language Optional, will override $.formUtils.LANG
|
|
|
138 |
* @param {Object} settings Optional, will override the default settings
|
|
|
139 |
* * @return {jQuery}
|
|
|
140 |
*/
|
|
|
141 |
$.fn.validateOnEvent = function (language, settings) {
|
|
|
142 |
this.find('input[data-validation][data-validation-event],textarea[data-validation][data-validation-event],select[data-validation][data-validation-event]')
|
|
|
143 |
.each(function () {
|
|
|
144 |
var $el = $(this),
|
|
|
145 |
etype = $el.valAttr("event");
|
|
|
146 |
if (etype) {
|
|
|
147 |
$el.bind(etype + ".validation", function () {
|
|
|
148 |
$(this).validateInputOnBlur(language, settings, true, etype);
|
|
|
149 |
});
|
|
|
150 |
}
|
|
|
151 |
});
|
|
|
152 |
return this;
|
|
|
153 |
};
|
|
|
154 |
|
|
|
155 |
/**
|
|
|
156 |
* fade in help message when input gains focus
|
|
|
157 |
* fade out when input loses focus
|
|
|
158 |
* <input data-help="The info that I want to display for the user when input is focused" ... />
|
|
|
159 |
*
|
|
|
160 |
* @param {String} attrName - Optional, default is data-help
|
|
|
161 |
* @return {jQuery}
|
|
|
162 |
*/
|
|
|
163 |
$.fn.showHelpOnFocus = function (attrName) {
|
|
|
164 |
if (!attrName) {
|
|
|
165 |
attrName = 'data-validation-help';
|
|
|
166 |
}
|
|
|
167 |
|
|
|
168 |
// Remove previously added event listeners
|
|
|
169 |
this.find('.has-help-txt')
|
|
|
170 |
.valAttr('has-keyup-event', false)
|
|
|
171 |
.removeClass('has-help-txt');
|
|
|
172 |
|
|
|
173 |
// Add help text listeners
|
|
|
174 |
this.find('textarea,input').each(function () {
|
|
|
175 |
var $elem = $(this),
|
|
|
176 |
className = 'jquery_form_help_' + ($elem.attr('name') || '').replace(/(:|\.|\[|\])/g, ""),
|
|
|
177 |
help = $elem.attr(attrName);
|
|
|
178 |
|
|
|
179 |
if (help) {
|
|
|
180 |
$elem
|
|
|
181 |
.addClass('has-help-txt')
|
|
|
182 |
.unbind('focus.help')
|
|
|
183 |
.bind('focus.help', function () {
|
|
|
184 |
var $help = $elem.parent().find('.' + className);
|
|
|
185 |
if ($help.length == 0) {
|
|
|
186 |
$help = $('<span />')
|
|
|
187 |
.addClass(className)
|
|
|
188 |
.addClass('help')
|
|
|
189 |
.addClass('help-block') // twitter bs
|
|
|
190 |
.text(help)
|
|
|
191 |
.hide();
|
|
|
192 |
|
|
|
193 |
$elem.after($help);
|
|
|
194 |
}
|
|
|
195 |
$help.fadeIn();
|
|
|
196 |
})
|
|
|
197 |
.unbind('blur.help')
|
|
|
198 |
.bind('blur.help', function () {
|
|
|
199 |
$(this)
|
|
|
200 |
.parent()
|
|
|
201 |
.find('.' + className)
|
|
|
202 |
.fadeOut('slow');
|
|
|
203 |
});
|
|
|
204 |
}
|
|
|
205 |
});
|
|
|
206 |
|
|
|
207 |
return this;
|
|
|
208 |
};
|
|
|
209 |
|
|
|
210 |
/**
|
|
|
211 |
* Validate single input when it loses focus
|
|
|
212 |
* shows error message in a span element
|
|
|
213 |
* that is appended to the parent element
|
|
|
214 |
*
|
|
|
215 |
* @param {Object} [language] Optional, will override $.formUtils.LANG
|
|
|
216 |
* @param {Object} [conf] Optional, will override the default settings
|
|
|
217 |
* @param {Boolean} attachKeyupEvent Optional
|
|
|
218 |
* @param {String} eventType
|
|
|
219 |
* @return {jQuery}
|
|
|
220 |
*/
|
|
|
221 |
$.fn.validateInputOnBlur = function (language, conf, attachKeyupEvent, eventType) {
|
|
|
222 |
|
|
|
223 |
$.formUtils.eventType = eventType;
|
|
|
224 |
|
|
|
225 |
if ((this.valAttr('suggestion-nr') || this.valAttr('postpone') || this.hasClass('hasDatepicker')) && !window.postponedValidation) {
|
|
|
226 |
// This validation has to be postponed
|
|
|
227 |
var _self = this,
|
|
|
228 |
postponeTime = this.valAttr('postpone') || 200;
|
|
|
229 |
|
|
|
230 |
window.postponedValidation = function () {
|
|
|
231 |
_self.validateInputOnBlur(language, conf, attachKeyupEvent, eventType);
|
|
|
232 |
window.postponedValidation = false;
|
|
|
233 |
};
|
|
|
234 |
|
|
|
235 |
setTimeout(function () {
|
|
|
236 |
if (window.postponedValidation) {
|
|
|
237 |
window.postponedValidation();
|
|
|
238 |
}
|
|
|
239 |
}, postponeTime);
|
|
|
240 |
|
|
|
241 |
return this;
|
|
|
242 |
}
|
|
|
243 |
|
|
|
244 |
language = $.extend({}, $.formUtils.LANG, language || {});
|
|
|
245 |
_removeErrorStyle(this, conf);
|
|
|
246 |
|
|
|
247 |
var $elem = this,
|
|
|
248 |
$form = $elem.closest("form"),
|
|
|
249 |
validationRule = $elem.attr(conf.validationRuleAttribute),
|
|
|
250 |
validation = $.formUtils.validateInput(
|
|
|
251 |
$elem,
|
|
|
252 |
language,
|
|
|
253 |
$.extend({}, conf, {errorMessagePosition: 'element'}),
|
|
|
254 |
$form,
|
|
|
255 |
eventType
|
|
|
256 |
);
|
|
|
257 |
|
|
|
258 |
if (validation === true) {
|
|
|
259 |
$elem.addClass('valid');
|
|
|
260 |
_getInputParentContainer($elem)
|
|
|
261 |
.addClass(conf.inputParentClassOnSuccess);
|
|
|
262 |
}
|
|
|
263 |
else if (validation !== null) {
|
|
|
264 |
|
|
|
265 |
_applyErrorStyle($elem, conf);
|
|
|
266 |
_setInlineErrorMessage($elem, validation, conf, conf.errorMessagePosition);
|
|
|
267 |
|
|
|
268 |
if (attachKeyupEvent) {
|
|
|
269 |
$elem
|
|
|
270 |
.unbind('keyup.validation')
|
|
|
271 |
.bind('keyup.validation', function () {
|
|
|
272 |
$(this).validateInputOnBlur(language, conf, false, 'keyup');
|
|
|
273 |
});
|
|
|
274 |
}
|
|
|
275 |
}
|
|
|
276 |
return this;
|
|
|
277 |
};
|
|
|
278 |
|
|
|
279 |
/**
|
|
|
280 |
* Short hand for fetching/adding/removing element attributes
|
|
|
281 |
* prefixed with 'data-validation-'
|
|
|
282 |
*
|
|
|
283 |
* @param {String} name
|
|
|
284 |
* @param {String|Boolean} [val]
|
|
|
285 |
* @return string|undefined
|
|
|
286 |
* @protected
|
|
|
287 |
*/
|
|
|
288 |
$.fn.valAttr = function (name, val) {
|
|
|
289 |
if (val === undefined) {
|
|
|
290 |
return this.attr('data-validation-' + name);
|
|
|
291 |
} else if (val === false || val === null) {
|
|
|
292 |
return this.removeAttr('data-validation-' + name);
|
|
|
293 |
} else {
|
|
|
294 |
if (name.length > 0) name = '-' + name;
|
|
|
295 |
return this.attr('data-validation' + name, val);
|
|
|
296 |
}
|
|
|
297 |
};
|
|
|
298 |
|
|
|
299 |
/**
|
|
|
300 |
* Function that validates all inputs in active form
|
|
|
301 |
*
|
|
|
302 |
* @param {Object} [language]
|
|
|
303 |
* @param {Object} [conf]
|
|
|
304 |
* @param {Boolean} [displayError] Defaults to true
|
|
|
305 |
*/
|
|
|
306 |
$.fn.isValid = function (language, conf, displayError) {
|
|
|
307 |
|
|
|
308 |
if ($.formUtils.isLoadingModules) {
|
|
|
309 |
var $self = this;
|
|
|
310 |
setTimeout(function () {
|
|
|
311 |
$self.isValid(language, conf, displayError);
|
|
|
312 |
}, 200);
|
|
|
313 |
return null;
|
|
|
314 |
}
|
|
|
315 |
|
|
|
316 |
conf = $.extend({}, $.formUtils.defaultConfig(), conf || {});
|
|
|
317 |
language = $.extend({}, $.formUtils.LANG, language || {});
|
|
|
318 |
displayError = displayError !== false;
|
|
|
319 |
|
|
|
320 |
if ($.formUtils.errorDisplayPreventedWhenHalted) {
|
|
|
321 |
// isValid() was called programmatically with argument displayError set
|
|
|
322 |
// to false when the validation was halted by any of the validators
|
|
|
323 |
delete $.formUtils.errorDisplayPreventedWhenHalted
|
|
|
324 |
displayError = false;
|
|
|
325 |
}
|
|
|
326 |
|
|
|
327 |
|
|
|
328 |
$.formUtils.isValidatingEntireForm = true;
|
|
|
329 |
$.formUtils.haltValidation = false;
|
|
|
330 |
|
|
|
331 |
/**
|
|
|
332 |
* Adds message to error message stack if not already in the message stack
|
|
|
333 |
*
|
|
|
334 |
* @param {String} mess
|
|
|
335 |
* @para {jQuery} $elem
|
|
|
336 |
*/
|
|
|
337 |
var addErrorMessage = function (mess, $elem) {
|
|
|
338 |
if ($.inArray(mess, errorMessages) < 0) {
|
|
|
339 |
errorMessages.push(mess);
|
|
|
340 |
}
|
|
|
341 |
errorInputs.push($elem);
|
|
|
342 |
$elem.attr('current-error', mess);
|
|
|
343 |
if (displayError)
|
|
|
344 |
_applyErrorStyle($elem, conf);
|
|
|
345 |
},
|
|
|
346 |
|
|
|
347 |
/** Holds inputs (of type checkox or radio) already validated, to prevent recheck of mulitple checkboxes & radios */
|
|
|
348 |
checkedInputs = [],
|
|
|
349 |
|
|
|
350 |
/** Error messages for this validation */
|
|
|
351 |
errorMessages = [],
|
|
|
352 |
|
|
|
353 |
/** Input elements which value was not valid */
|
|
|
354 |
errorInputs = [],
|
|
|
355 |
|
|
|
356 |
/** Form instance */
|
|
|
357 |
$form = this,
|
|
|
358 |
|
|
|
359 |
/**
|
|
|
360 |
* Tells whether or not to validate element with this name and of this type
|
|
|
361 |
*
|
|
|
362 |
* @param {String} name
|
|
|
363 |
* @param {String} type
|
|
|
364 |
* @return {Boolean}
|
|
|
365 |
*/
|
|
|
366 |
ignoreInput = function (name, type) {
|
|
|
367 |
if (type === 'submit' || type === 'button' || type == 'reset') {
|
|
|
368 |
return true;
|
|
|
369 |
}
|
|
|
370 |
return $.inArray(name, conf.ignore || []) > -1;
|
|
|
371 |
};
|
|
|
372 |
|
|
|
373 |
// Reset style and remove error class
|
|
|
374 |
if (displayError) {
|
|
|
375 |
$form.find('.' + conf.errorMessageClass + '.alert').remove();
|
|
|
376 |
_removeErrorStyle($form.find('.' + conf.errorElementClass + ',.valid'), conf);
|
|
|
377 |
}
|
|
|
378 |
|
|
|
379 |
// Validate element values
|
|
|
380 |
$form.find('input,textarea,select').filter(':not([type="submit"],[type="button"])').each(function () {
|
|
|
381 |
var $elem = $(this),
|
|
|
382 |
elementType = $elem.attr('type'),
|
|
|
383 |
isCheckboxOrRadioBtn = elementType == 'radio' || elementType == 'checkbox',
|
|
|
384 |
elementName = $elem.attr('name');
|
|
|
385 |
|
|
|
386 |
if (!ignoreInput(elementName, elementType) && (!isCheckboxOrRadioBtn || $.inArray(elementName, checkedInputs) < 0)) {
|
|
|
387 |
|
|
|
388 |
if (isCheckboxOrRadioBtn)
|
|
|
389 |
checkedInputs.push(elementName);
|
|
|
390 |
|
|
|
391 |
var validation = $.formUtils.validateInput(
|
|
|
392 |
$elem,
|
|
|
393 |
language,
|
|
|
394 |
conf,
|
|
|
395 |
$form,
|
|
|
396 |
'submit'
|
|
|
397 |
);
|
|
|
398 |
|
|
|
399 |
if (validation != null) {
|
|
|
400 |
if (validation !== true) {
|
|
|
401 |
addErrorMessage(validation, $elem);
|
|
|
402 |
} else {
|
|
|
403 |
$elem
|
|
|
404 |
.valAttr('current-error', false)
|
|
|
405 |
.addClass('valid');
|
|
|
406 |
|
|
|
407 |
_getInputParentContainer($elem).addClass(conf.inputParentClassOnSuccess);
|
|
|
408 |
}
|
|
|
409 |
}
|
|
|
410 |
}
|
|
|
411 |
});
|
|
|
412 |
|
|
|
413 |
// Run validation callback
|
|
|
414 |
if (typeof conf.onValidate == 'function') {
|
|
|
415 |
var errors = conf.onValidate($form);
|
|
|
416 |
if ($.isArray(errors)) {
|
|
|
417 |
$.each(errors, function (i, err) {
|
|
|
418 |
addErrorMessage(err.message, err.element);
|
|
|
419 |
});
|
|
|
420 |
}
|
|
|
421 |
else if (errors && errors.element && errors.message) {
|
|
|
422 |
addErrorMessage(errors.message, errors.element);
|
|
|
423 |
}
|
|
|
424 |
}
|
|
|
425 |
|
|
|
426 |
// Reset form validation flag
|
|
|
427 |
$.formUtils.isValidatingEntireForm = false;
|
|
|
428 |
|
|
|
429 |
// Validation failed
|
|
|
430 |
if (!$.formUtils.haltValidation && errorInputs.length > 0) {
|
|
|
431 |
|
|
|
432 |
if (displayError) {
|
|
|
433 |
// display all error messages in top of form
|
|
|
434 |
if (conf.errorMessagePosition === 'top') {
|
|
|
435 |
_templateMessage($form, language.errorTitle, errorMessages, conf);
|
|
|
436 |
}
|
|
|
437 |
// Customize display message
|
|
|
438 |
else if (conf.errorMessagePosition === 'custom') {
|
|
|
439 |
if (typeof conf.errorMessageCustom === 'function') {
|
|
|
440 |
conf.errorMessageCustom($form, language.errorTitle, errorMessages, conf);
|
|
|
441 |
}
|
|
|
442 |
}
|
|
|
443 |
// Display error message below input field or in defined container
|
|
|
444 |
else {
|
|
|
445 |
$.each(errorInputs, function (i, $input) {
|
|
|
446 |
_setInlineErrorMessage($input, $input.attr('current-error'), conf, conf.errorMessagePosition);
|
|
|
447 |
});
|
|
|
448 |
}
|
|
|
449 |
|
|
|
450 |
if (conf.scrollToTopOnError) {
|
|
|
451 |
$window.scrollTop($form.offset().top - 20);
|
|
|
452 |
}
|
|
|
453 |
}
|
|
|
454 |
|
|
|
455 |
return false;
|
|
|
456 |
}
|
|
|
457 |
|
|
|
458 |
if (!displayError && $.formUtils.haltValidation) {
|
|
|
459 |
$.formUtils.errorDisplayPreventedWhenHalted = true;
|
|
|
460 |
}
|
|
|
461 |
|
|
|
462 |
return !$.formUtils.haltValidation;
|
|
|
463 |
};
|
|
|
464 |
|
|
|
465 |
/**
|
|
|
466 |
* @deprecated
|
|
|
467 |
* @param language
|
|
|
468 |
* @param conf
|
|
|
469 |
*/
|
|
|
470 |
$.fn.validateForm = function (language, conf) {
|
|
|
471 |
if (window.console && typeof window.console.warn == 'function') {
|
|
|
472 |
window.console.warn('Use of deprecated function $.validateForm, use $.isValid instead');
|
|
|
473 |
}
|
|
|
474 |
return this.isValid(language, conf, true);
|
|
|
475 |
}
|
|
|
476 |
|
|
|
477 |
/**
|
|
|
478 |
* Plugin for displaying input length restriction
|
|
|
479 |
*/
|
|
|
480 |
$.fn.restrictLength = function (maxLengthElement) {
|
|
|
481 |
new $.formUtils.lengthRestriction(this, maxLengthElement);
|
|
|
482 |
return this;
|
|
|
483 |
};
|
|
|
484 |
|
|
|
485 |
/**
|
|
|
486 |
* Add suggestion dropdown to inputs having data-suggestions with a comma
|
|
|
487 |
* separated string with suggestions
|
|
|
488 |
* @param {Array} [settings]
|
|
|
489 |
* @returns {jQuery}
|
|
|
490 |
*/
|
|
|
491 |
$.fn.addSuggestions = function (settings) {
|
|
|
492 |
var sugs = false;
|
|
|
493 |
this.find('input').each(function () {
|
|
|
494 |
var $field = $(this);
|
|
|
495 |
|
|
|
496 |
sugs = $.split($field.attr('data-suggestions'));
|
|
|
497 |
|
|
|
498 |
if (sugs.length > 0 && !$field.hasClass('has-suggestions')) {
|
|
|
499 |
$.formUtils.suggest($field, sugs, settings);
|
|
|
500 |
$field.addClass('has-suggestions');
|
|
|
501 |
}
|
|
|
502 |
});
|
|
|
503 |
return this;
|
|
|
504 |
};
|
|
|
505 |
|
|
|
506 |
/**
|
|
|
507 |
* A bit smarter split function
|
|
|
508 |
* delimiter can be space, comma, dash or pipe
|
|
|
509 |
* @param {String} val
|
|
|
510 |
* @param {Function|String} [func]
|
|
|
511 |
* @returns {Array|void}
|
|
|
512 |
*/
|
|
|
513 |
$.split = function (val, func) {
|
|
|
514 |
if (typeof func != 'function') {
|
|
|
515 |
// return array
|
|
|
516 |
if (!val)
|
|
|
517 |
return [];
|
|
|
518 |
var values = [];
|
|
|
519 |
$.each(val.split(func ? func : /[,|\-\s]\s*/g),
|
|
|
520 |
function (i, str) {
|
|
|
521 |
str = $.trim(str);
|
|
|
522 |
if (str.length)
|
|
|
523 |
values.push(str);
|
|
|
524 |
}
|
|
|
525 |
);
|
|
|
526 |
return values;
|
|
|
527 |
} else if (val) {
|
|
|
528 |
// exec callback func on each
|
|
|
529 |
$.each(val.split(/[,|\-\s]\s*/g),
|
|
|
530 |
function (i, str) {
|
|
|
531 |
str = $.trim(str);
|
|
|
532 |
if (str.length)
|
|
|
533 |
return func(str, i);
|
|
|
534 |
}
|
|
|
535 |
);
|
|
|
536 |
}
|
|
|
537 |
};
|
|
|
538 |
|
|
|
539 |
/**
|
|
|
540 |
* Short hand function that makes the validation setup require less code
|
|
|
541 |
* @param conf
|
|
|
542 |
*/
|
|
|
543 |
$.validate = function (conf) {
|
|
|
544 |
|
|
|
545 |
var defaultConf = $.extend($.formUtils.defaultConfig(), {
|
|
|
546 |
form: 'form',
|
|
|
547 |
/*
|
|
|
548 |
* Enable custom event for validation
|
|
|
549 |
*/
|
|
|
550 |
validateOnEvent: true,
|
|
|
551 |
validateOnBlur: true,
|
|
|
552 |
validateCheckboxRadioOnClick: true,
|
|
|
553 |
showHelpOnFocus: true,
|
|
|
554 |
addSuggestions: true,
|
|
|
555 |
modules: '',
|
|
|
556 |
onModulesLoaded: null,
|
|
|
557 |
language: false,
|
|
|
558 |
onSuccess: false,
|
|
|
559 |
onError: false,
|
|
|
560 |
onElementValidate: false,
|
|
|
561 |
});
|
|
|
562 |
|
|
|
563 |
conf = $.extend(defaultConf, conf || {});
|
|
|
564 |
|
|
|
565 |
// Add validation to forms
|
|
|
566 |
$(conf.form).each(function (i, form) {
|
|
|
567 |
|
|
|
568 |
var $form = $(form);
|
|
|
569 |
$window.trigger('formValidationSetup', [$form]);
|
|
|
570 |
|
|
|
571 |
// Remove all event listeners previously added
|
|
|
572 |
$form.find('.has-help-txt')
|
|
|
573 |
.unbind('focus.validation')
|
|
|
574 |
.unbind('blur.validation');
|
|
|
575 |
$form
|
|
|
576 |
.removeClass('has-validation-callback')
|
|
|
577 |
.unbind('submit.validation')
|
|
|
578 |
.unbind('reset.validation')
|
|
|
579 |
.find('input[data-validation],textarea[data-validation]')
|
|
|
580 |
.unbind('blur.validation');
|
|
|
581 |
|
|
|
582 |
// Validate when submitted
|
|
|
583 |
$form.bind('submit.validation', function () {
|
|
|
584 |
var $form = $(this);
|
|
|
585 |
|
|
|
586 |
if ($.formUtils.haltValidation) {
|
|
|
587 |
// pressing several times on submit button while validation is halted
|
|
|
588 |
return false;
|
|
|
589 |
}
|
|
|
590 |
|
|
|
591 |
if ($.formUtils.isLoadingModules) {
|
|
|
592 |
setTimeout(function () {
|
|
|
593 |
$form.trigger('submit.validation');
|
|
|
594 |
}, 200);
|
|
|
595 |
return false;
|
|
|
596 |
}
|
|
|
597 |
|
|
|
598 |
var valid = $form.isValid(conf.language, conf);
|
|
|
599 |
|
|
|
600 |
if ($.formUtils.haltValidation) {
|
|
|
601 |
// Validation got halted by one of the validators
|
|
|
602 |
return false;
|
|
|
603 |
} else {
|
|
|
604 |
if (valid && typeof conf.onSuccess == 'function') {
|
|
|
605 |
var callbackResponse = conf.onSuccess($form);
|
|
|
606 |
if (callbackResponse === false)
|
|
|
607 |
return false;
|
|
|
608 |
} else if (!valid && typeof conf.onError == 'function') {
|
|
|
609 |
conf.onError($form);
|
|
|
610 |
return false;
|
|
|
611 |
} else {
|
|
|
612 |
return valid;
|
|
|
613 |
}
|
|
|
614 |
}
|
|
|
615 |
})
|
|
|
616 |
.bind('reset.validation', function () {
|
|
|
617 |
// remove messages
|
|
|
618 |
$(this).find('.' + conf.errorMessageClass + '.alert').remove();
|
|
|
619 |
_removeErrorStyle($(this).find('.' + conf.errorElementClass + ',.valid'), conf);
|
|
|
620 |
})
|
|
|
621 |
.addClass('has-validation-callback');
|
|
|
622 |
|
|
|
623 |
if (conf.showHelpOnFocus) {
|
|
|
624 |
$form.showHelpOnFocus();
|
|
|
625 |
}
|
|
|
626 |
if (conf.addSuggestions) {
|
|
|
627 |
$form.addSuggestions();
|
|
|
628 |
}
|
|
|
629 |
if (conf.validateOnBlur) {
|
|
|
630 |
$form.validateOnBlur(conf.language, conf);
|
|
|
631 |
$form.bind('html5ValidationAttrsFound', function () {
|
|
|
632 |
$form.validateOnBlur(conf.language, conf);
|
|
|
633 |
})
|
|
|
634 |
}
|
|
|
635 |
if (conf.validateOnEvent) {
|
|
|
636 |
$form.validateOnEvent(conf.language, conf);
|
|
|
637 |
}
|
|
|
638 |
});
|
|
|
639 |
|
|
|
640 |
if (conf.modules != '') {
|
|
|
641 |
if (typeof conf.onModulesLoaded == 'function') {
|
|
|
642 |
$window.one('validatorsLoaded', conf.onModulesLoaded);
|
|
|
643 |
}
|
|
|
644 |
$.formUtils.loadModules(conf.modules);
|
|
|
645 |
}
|
|
|
646 |
};
|
|
|
647 |
|
|
|
648 |
/**
|
|
|
649 |
* Object containing utility methods for this plugin
|
|
|
650 |
*/
|
|
|
651 |
$.formUtils = {
|
|
|
652 |
|
|
|
653 |
/**
|
|
|
654 |
* Default config for $(...).isValid();
|
|
|
655 |
*/
|
|
|
656 |
defaultConfig: function () {
|
|
|
657 |
return {
|
|
|
658 |
ignore: [], // Names of inputs not to be validated even though node attribute containing the validation rules tells us to
|
|
|
659 |
errorElementClass: 'error', // Class that will be put on elements which value is invalid
|
|
|
660 |
borderColorOnError: 'red', // Border color of elements which value is invalid, empty string to not change border color
|
|
|
661 |
errorMessageClass: 'form-error', // class name of div containing error messages when validation fails
|
|
|
662 |
validationRuleAttribute: 'data-validation', // name of the attribute holding the validation rules
|
|
|
663 |
validationErrorMsgAttribute: 'data-validation-error-msg', // define custom err msg inline with element
|
|
|
664 |
errorMessagePosition: 'element', // Can be either "top" or "element" or "custom"
|
|
|
665 |
errorMessageTemplate: {
|
|
|
666 |
container: '<div class="{errorMessageClass} alert alert-danger">{messages}</div>',
|
|
|
667 |
messages: '<strong>{errorTitle}</strong><ul>{fields}</ul>',
|
|
|
668 |
field: '<li>{msg}</li>'
|
|
|
669 |
},
|
|
|
670 |
errorMessageCustom: _templateMessage,
|
|
|
671 |
scrollToTopOnError: true,
|
|
|
672 |
dateFormat: 'yyyy-mm-dd',
|
|
|
673 |
addValidClassOnAll: false, // whether or not to apply class="valid" even if the input wasn't validated
|
|
|
674 |
decimalSeparator: '.',
|
|
|
675 |
inputParentClassOnError: 'has-error', // twitter-bootstrap default class name
|
|
|
676 |
inputParentClassOnSuccess: 'has-success' // twitter-bootstrap default class name
|
|
|
677 |
}
|
|
|
678 |
},
|
|
|
679 |
|
|
|
680 |
/**
|
|
|
681 |
* Available validators
|
|
|
682 |
*/
|
|
|
683 |
validators: {},
|
|
|
684 |
|
|
|
685 |
/**
|
|
|
686 |
* Events triggered by form validator
|
|
|
687 |
*/
|
|
|
688 |
_events: {load: [], valid: [], invalid: []},
|
|
|
689 |
|
|
|
690 |
/**
|
|
|
691 |
* Setting this property to true during validation will
|
|
|
692 |
* stop further validation from taking place and form will
|
|
|
693 |
* not be sent
|
|
|
694 |
*/
|
|
|
695 |
haltValidation: false,
|
|
|
696 |
|
|
|
697 |
/**
|
|
|
698 |
* This variable will be true $.fn.isValid() is called
|
|
|
699 |
* and false when $.fn.validateOnBlur is called
|
|
|
700 |
*/
|
|
|
701 |
isValidatingEntireForm: false,
|
|
|
702 |
|
|
|
703 |
/**
|
|
|
704 |
* Function for adding a validator
|
|
|
705 |
* @param {Object} validator
|
|
|
706 |
*/
|
|
|
707 |
addValidator: function (validator) {
|
|
|
708 |
// prefix with "validate_" for backward compatibility reasons
|
|
|
709 |
var name = validator.name.indexOf('validate_') === 0 ? validator.name : 'validate_' + validator.name;
|
|
|
710 |
if (validator.validateOnKeyUp === undefined)
|
|
|
711 |
validator.validateOnKeyUp = true;
|
|
|
712 |
this.validators[name] = validator;
|
|
|
713 |
},
|
|
|
714 |
|
|
|
715 |
/**
|
|
|
716 |
* @var {Boolean}
|
|
|
717 |
*/
|
|
|
718 |
isLoadingModules: false,
|
|
|
719 |
|
|
|
720 |
/**
|
|
|
721 |
* @var {Object}
|
|
|
722 |
*/
|
|
|
723 |
loadedModules: {},
|
|
|
724 |
|
|
|
725 |
/**
|
|
|
726 |
* @example
|
|
|
727 |
* $.formUtils.loadModules('date, security.dev');
|
|
|
728 |
*
|
|
|
729 |
* Will load the scripts date.js and security.dev.js from the
|
|
|
730 |
* directory where this script resides. If you want to load
|
|
|
731 |
* the modules from another directory you can use the
|
|
|
732 |
* path argument.
|
|
|
733 |
*
|
|
|
734 |
* The script will be cached by the browser unless the module
|
|
|
735 |
* name ends with .dev
|
|
|
736 |
*
|
|
|
737 |
* @param {String} modules - Comma separated string with module file names (no directory nor file extension)
|
|
|
738 |
* @param {String} [path] - Optional, path where the module files is located if their not in the same directory as the core modules
|
|
|
739 |
* @param {Boolean} [fireEvent] - Optional, whether or not to fire event 'load' when modules finished loading
|
|
|
740 |
*/
|
|
|
741 |
loadModules: function (modules, path, fireEvent) {
|
|
|
742 |
|
|
|
743 |
if (fireEvent === undefined)
|
|
|
744 |
fireEvent = true;
|
|
|
745 |
|
|
|
746 |
if ($.formUtils.isLoadingModules) {
|
|
|
747 |
setTimeout(function () {
|
|
|
748 |
$.formUtils.loadModules(modules, path, fireEvent);
|
|
|
749 |
});
|
|
|
750 |
return;
|
|
|
751 |
}
|
|
|
752 |
|
|
|
753 |
var hasLoadedAnyModule = false,
|
|
|
754 |
loadModuleScripts = function (modules, path) {
|
|
|
755 |
|
|
|
756 |
var moduleList = $.split(modules),
|
|
|
757 |
numModules = moduleList.length,
|
|
|
758 |
moduleLoadedCallback = function () {
|
|
|
759 |
numModules--;
|
|
|
760 |
if (numModules == 0) {
|
|
|
761 |
$.formUtils.isLoadingModules = false;
|
|
|
762 |
if (fireEvent && hasLoadedAnyModule) {
|
|
|
763 |
$window.trigger('validatorsLoaded');
|
|
|
764 |
}
|
|
|
765 |
}
|
|
|
766 |
};
|
|
|
767 |
|
|
|
768 |
if (numModules > 0) {
|
|
|
769 |
$.formUtils.isLoadingModules = true;
|
|
|
770 |
}
|
|
|
771 |
|
|
|
772 |
var cacheSuffix = '?__=' + ( new Date().getTime() ),
|
|
|
773 |
appendToElement = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];
|
|
|
774 |
|
|
|
775 |
$.each(moduleList, function (i, modName) {
|
|
|
776 |
modName = $.trim(modName);
|
|
|
777 |
if (modName.length == 0) {
|
|
|
778 |
moduleLoadedCallback();
|
|
|
779 |
}
|
|
|
780 |
else {
|
|
|
781 |
var scriptUrl = path + modName + (modName.substr(-3) == '.js' ? '' : '.js'),
|
|
|
782 |
script = document.createElement('SCRIPT');
|
|
|
783 |
|
|
|
784 |
if (scriptUrl in $.formUtils.loadedModules) {
|
|
|
785 |
// already loaded
|
|
|
786 |
moduleLoadedCallback();
|
|
|
787 |
}
|
|
|
788 |
else {
|
|
|
789 |
|
|
|
790 |
// Remember that this script is loaded
|
|
|
791 |
$.formUtils.loadedModules[scriptUrl] = 1;
|
|
|
792 |
hasLoadedAnyModule = true;
|
|
|
793 |
|
|
|
794 |
// Load the script
|
|
|
795 |
script.type = 'text/javascript';
|
|
|
796 |
script.onload = moduleLoadedCallback;
|
|
|
797 |
script.src = scriptUrl + ( scriptUrl.substr(-7) == '.dev.js' ? cacheSuffix : '' );
|
|
|
798 |
script.onreadystatechange = function () {
|
|
|
799 |
// IE 7 fix
|
|
|
800 |
if (this.readyState == 'complete' || this.readyState == 'loaded') {
|
|
|
801 |
moduleLoadedCallback();
|
|
|
802 |
// Handle memory leak in IE
|
|
|
803 |
this.onload = null;
|
|
|
804 |
this.onreadystatechange = null;
|
|
|
805 |
}
|
|
|
806 |
};
|
|
|
807 |
appendToElement.appendChild(script);
|
|
|
808 |
}
|
|
|
809 |
}
|
|
|
810 |
});
|
|
|
811 |
};
|
|
|
812 |
|
|
|
813 |
if (path) {
|
|
|
814 |
loadModuleScripts(modules, path);
|
|
|
815 |
} else {
|
|
|
816 |
var findScriptPathAndLoadModules = function () {
|
|
|
817 |
var foundPath = false;
|
|
|
818 |
$('script[src*="form-validator"]').each(function () {
|
|
|
819 |
foundPath = this.src.substr(0, this.src.lastIndexOf('/')) + '/';
|
|
|
820 |
if (foundPath == '/')
|
|
|
821 |
foundPath = '';
|
|
|
822 |
return false;
|
|
|
823 |
});
|
|
|
824 |
|
|
|
825 |
if (foundPath !== false) {
|
|
|
826 |
loadModuleScripts(modules, foundPath);
|
|
|
827 |
return true;
|
|
|
828 |
}
|
|
|
829 |
return false;
|
|
|
830 |
};
|
|
|
831 |
|
|
|
832 |
if (!findScriptPathAndLoadModules()) {
|
|
|
833 |
$(findScriptPathAndLoadModules);
|
|
|
834 |
}
|
|
|
835 |
}
|
|
|
836 |
},
|
|
|
837 |
|
|
|
838 |
/**
|
|
|
839 |
* Validate the value of given element according to the validation rules
|
|
|
840 |
* found in the attribute data-validation. Will return null if no validation
|
|
|
841 |
* should take place, returns true if valid or error message if not valid
|
|
|
842 |
*
|
|
|
843 |
* @param {jQuery} $elem
|
|
|
844 |
* @param {Object} language ($.formUtils.LANG)
|
|
|
845 |
* @param {Object} conf
|
|
|
846 |
* @param {jQuery} $form
|
|
|
847 |
* @param {String} [eventContext]
|
|
|
848 |
* @return {String|Boolean}
|
|
|
849 |
*/
|
|
|
850 |
validateInput: function ($elem, language, conf, $form, eventContext) {
|
|
|
851 |
|
|
|
852 |
if ($elem.attr('disabled'))
|
|
|
853 |
return null; // returning null will prevent that the valid class gets applied to the element
|
|
|
854 |
|
|
|
855 |
$elem.trigger('beforeValidation');
|
|
|
856 |
|
|
|
857 |
var value = $elem.val() || '',
|
|
|
858 |
optional = $elem.valAttr('optional'),
|
|
|
859 |
|
|
|
860 |
// test if a checkbox forces this element to be validated
|
|
|
861 |
validationDependsOnCheckedInput = false,
|
|
|
862 |
validationDependentInputIsChecked = false,
|
|
|
863 |
validateIfCheckedElement = false,
|
|
|
864 |
|
|
|
865 |
// get value of this element's attribute "... if-checked"
|
|
|
866 |
validateIfCheckedElementName = $elem.valAttr("if-checked");
|
|
|
867 |
|
|
|
868 |
// make sure we can proceed
|
|
|
869 |
if (validateIfCheckedElementName != null) {
|
|
|
870 |
|
|
|
871 |
// Set the boolean telling us that the validation depends
|
|
|
872 |
// on another input being checked
|
|
|
873 |
validationDependsOnCheckedInput = true;
|
|
|
874 |
|
|
|
875 |
// select the checkbox type element in this form
|
|
|
876 |
validateIfCheckedElement = $form.find('input[name="' + validateIfCheckedElementName + '"]');
|
|
|
877 |
|
|
|
878 |
// test if it's property "checked" is checked
|
|
|
879 |
if (validateIfCheckedElement.prop('checked')) {
|
|
|
880 |
// set value for validation checkpoint
|
|
|
881 |
validationDependentInputIsChecked = true;
|
|
|
882 |
}
|
|
|
883 |
}
|
|
|
884 |
|
|
|
885 |
// validation checkpoint
|
|
|
886 |
// if empty AND optional attribute is present
|
|
|
887 |
// OR depending on a checkbox being checked AND checkbox is checked, return true
|
|
|
888 |
if ((!value && optional === 'true') || (validationDependsOnCheckedInput && !validationDependentInputIsChecked)) {
|
|
|
889 |
return conf.addValidClassOnAll ? true : null;
|
|
|
890 |
}
|
|
|
891 |
|
|
|
892 |
var validationRules = $elem.attr(conf.validationRuleAttribute),
|
|
|
893 |
|
|
|
894 |
// see if form element has inline err msg attribute
|
|
|
895 |
validationErrorMsg = true;
|
|
|
896 |
|
|
|
897 |
if (!validationRules) {
|
|
|
898 |
return conf.addValidClassOnAll ? true : null;
|
|
|
899 |
}
|
|
|
900 |
|
|
|
901 |
$.split(validationRules, function (rule) {
|
|
|
902 |
if (rule.indexOf('validate_') !== 0) {
|
|
|
903 |
rule = 'validate_' + rule;
|
|
|
904 |
}
|
|
|
905 |
|
|
|
906 |
var validator = $.formUtils.validators[rule];
|
|
|
907 |
|
|
|
908 |
if (validator && typeof validator['validatorFunction'] == 'function') {
|
|
|
909 |
|
|
|
910 |
// special change of element for checkbox_group rule
|
|
|
911 |
if (rule == 'validate_checkbox_group') {
|
|
|
912 |
// set element to first in group, so error msg attr doesn't need to be set on all elements in group
|
|
|
913 |
$elem = $("[name='" + $elem.attr('name') + "']:eq(0)");
|
|
|
914 |
}
|
|
|
915 |
|
|
|
916 |
var isValid = null;
|
|
|
917 |
if (eventContext != 'keyup' || validator.validateOnKeyUp) {
|
|
|
918 |
isValid = validator.validatorFunction(value, $elem, conf, language, $form);
|
|
|
919 |
}
|
|
|
920 |
|
|
|
921 |
if (!isValid) {
|
|
|
922 |
validationErrorMsg = null;
|
|
|
923 |
if (isValid !== null) {
|
|
|
924 |
validationErrorMsg = $elem.attr(conf.validationErrorMsgAttribute + '-' + rule.replace('validate_', ''));
|
|
|
925 |
if (!validationErrorMsg) {
|
|
|
926 |
validationErrorMsg = $elem.attr(conf.validationErrorMsgAttribute);
|
|
|
927 |
if (!validationErrorMsg) {
|
|
|
928 |
validationErrorMsg = language[validator.errorMessageKey];
|
|
|
929 |
if (!validationErrorMsg)
|
|
|
930 |
validationErrorMsg = validator.errorMessage;
|
|
|
931 |
}
|
|
|
932 |
}
|
|
|
933 |
}
|
|
|
934 |
return false; // breaks the iteration
|
|
|
935 |
}
|
|
|
936 |
|
|
|
937 |
} else {
|
|
|
938 |
throw new Error('Using undefined validator "' + rule + '"');
|
|
|
939 |
}
|
|
|
940 |
|
|
|
941 |
}, ' ');
|
|
|
942 |
|
|
|
943 |
var result;
|
|
|
944 |
|
|
|
945 |
if (typeof validationErrorMsg == 'string') {
|
|
|
946 |
$elem.trigger('validation', false);
|
|
|
947 |
result = validationErrorMsg;
|
|
|
948 |
} else if (validationErrorMsg === null && !conf.addValidClassOnAll) {
|
|
|
949 |
result = null;
|
|
|
950 |
} else {
|
|
|
951 |
$elem.trigger('validation', true);
|
|
|
952 |
result = true;
|
|
|
953 |
}
|
|
|
954 |
|
|
|
955 |
// Run element validation callback
|
|
|
956 |
if (typeof conf.onElementValidate == 'function' && result !== null) {
|
|
|
957 |
conf.onElementValidate((result === true), $elem, $form, validationErrorMsg);
|
|
|
958 |
}
|
|
|
959 |
|
|
|
960 |
return result;
|
|
|
961 |
},
|
|
|
962 |
|
|
|
963 |
/**
|
|
|
964 |
* Is it a correct date according to given dateFormat. Will return false if not, otherwise
|
|
|
965 |
* an array 0=>year 1=>month 2=>day
|
|
|
966 |
*
|
|
|
967 |
* @param {String} val
|
|
|
968 |
* @param {String} dateFormat
|
|
|
969 |
* @return {Array}|{Boolean}
|
|
|
970 |
*/
|
|
|
971 |
parseDate: function (val, dateFormat) {
|
|
|
972 |
var divider = dateFormat.replace(/[a-zA-Z]/gi, '').substring(0, 1),
|
|
|
973 |
regexp = '^',
|
|
|
974 |
formatParts = dateFormat.split(divider || null),
|
|
|
975 |
matches, day, month, year;
|
|
|
976 |
|
|
|
977 |
$.each(formatParts, function (i, part) {
|
|
|
978 |
regexp += (i > 0 ? '\\' + divider : '') + '(\\d{' + part.length + '})';
|
|
|
979 |
});
|
|
|
980 |
|
|
|
981 |
regexp += '$';
|
|
|
982 |
|
|
|
983 |
matches = val.match(new RegExp(regexp));
|
|
|
984 |
if (matches === null) {
|
|
|
985 |
return false;
|
|
|
986 |
}
|
|
|
987 |
|
|
|
988 |
var findDateUnit = function (unit, formatParts, matches) {
|
|
|
989 |
for (var i = 0; i < formatParts.length; i++) {
|
|
|
990 |
if (formatParts[i].substring(0, 1) === unit) {
|
|
|
991 |
return $.formUtils.parseDateInt(matches[i + 1]);
|
|
|
992 |
}
|
|
|
993 |
}
|
|
|
994 |
return -1;
|
|
|
995 |
};
|
|
|
996 |
|
|
|
997 |
month = findDateUnit('m', formatParts, matches);
|
|
|
998 |
day = findDateUnit('d', formatParts, matches);
|
|
|
999 |
year = findDateUnit('y', formatParts, matches);
|
|
|
1000 |
|
|
|
1001 |
if ((month === 2 && day > 28 && (year % 4 !== 0 || year % 100 === 0 && year % 400 !== 0))
|
|
|
1002 |
|| (month === 2 && day > 29 && (year % 4 === 0 || year % 100 !== 0 && year % 400 === 0))
|
|
|
1003 |
|| month > 12 || month === 0) {
|
|
|
1004 |
return false;
|
|
|
1005 |
}
|
|
|
1006 |
if ((this.isShortMonth(month) && day > 30) || (!this.isShortMonth(month) && day > 31) || day === 0) {
|
|
|
1007 |
return false;
|
|
|
1008 |
}
|
|
|
1009 |
|
|
|
1010 |
return [year, month, day];
|
|
|
1011 |
},
|
|
|
1012 |
|
|
|
1013 |
/**
|
|
|
1014 |
* skum fix. är talet 05 eller lägre ger parseInt rätt int annars får man 0 när man kör parseInt?
|
|
|
1015 |
*
|
|
|
1016 |
* @param {String} val
|
|
|
1017 |
* @param {Number}
|
|
|
1018 |
*/
|
|
|
1019 |
parseDateInt: function (val) {
|
|
|
1020 |
if (val.indexOf('0') === 0) {
|
|
|
1021 |
val = val.replace('0', '');
|
|
|
1022 |
}
|
|
|
1023 |
return parseInt(val, 10);
|
|
|
1024 |
},
|
|
|
1025 |
|
|
|
1026 |
/**
|
|
|
1027 |
* Has month only 30 days?
|
|
|
1028 |
*
|
|
|
1029 |
* @param {Number} m
|
|
|
1030 |
* @return {Boolean}
|
|
|
1031 |
*/
|
|
|
1032 |
isShortMonth: function (m) {
|
|
|
1033 |
return (m % 2 === 0 && m < 7) || (m % 2 !== 0 && m > 7);
|
|
|
1034 |
},
|
|
|
1035 |
|
|
|
1036 |
/**
|
|
|
1037 |
* Restrict input length
|
|
|
1038 |
*
|
|
|
1039 |
* @param {jQuery} $inputElement Jquery Html object
|
|
|
1040 |
* @param {jQuery} $maxLengthElement jQuery Html Object
|
|
|
1041 |
* @return void
|
|
|
1042 |
*/
|
|
|
1043 |
lengthRestriction: function ($inputElement, $maxLengthElement) {
|
|
|
1044 |
// read maxChars from counter display initial text value
|
|
|
1045 |
var maxChars = parseInt($maxLengthElement.text(), 10),
|
|
|
1046 |
charsLeft = 0,
|
|
|
1047 |
|
|
|
1048 |
// internal function does the counting and sets display value
|
|
|
1049 |
countCharacters = function () {
|
|
|
1050 |
var numChars = $inputElement.val().length;
|
|
|
1051 |
if (numChars > maxChars) {
|
|
|
1052 |
// get current scroll bar position
|
|
|
1053 |
var currScrollTopPos = $inputElement.scrollTop();
|
|
|
1054 |
// trim value to max length
|
|
|
1055 |
$inputElement.val($inputElement.val().substring(0, maxChars));
|
|
|
1056 |
$inputElement.scrollTop(currScrollTopPos);
|
|
|
1057 |
}
|
|
|
1058 |
charsLeft = maxChars - numChars;
|
|
|
1059 |
if (charsLeft < 0)
|
|
|
1060 |
charsLeft = 0;
|
|
|
1061 |
|
|
|
1062 |
// set counter text
|
|
|
1063 |
$maxLengthElement.text(charsLeft);
|
|
|
1064 |
};
|
|
|
1065 |
|
|
|
1066 |
// bind events to this element
|
|
|
1067 |
// setTimeout is needed, cut or paste fires before val is available
|
|
|
1068 |
$($inputElement).bind('keydown keyup keypress focus blur', countCharacters)
|
|
|
1069 |
.bind('cut paste', function () {
|
|
|
1070 |
setTimeout(countCharacters, 100);
|
|
|
1071 |
});
|
|
|
1072 |
|
|
|
1073 |
// count chars on pageload, if there are prefilled input-values
|
|
|
1074 |
$(document).bind("ready", countCharacters);
|
|
|
1075 |
},
|
|
|
1076 |
|
|
|
1077 |
/**
|
|
|
1078 |
* Test numeric against allowed range
|
|
|
1079 |
*
|
|
|
1080 |
* @param $value int
|
|
|
1081 |
* @param $rangeAllowed str; (1-2, min1, max2)
|
|
|
1082 |
* @return array
|
|
|
1083 |
*/
|
|
|
1084 |
numericRangeCheck: function (value, rangeAllowed) {
|
|
|
1085 |
// split by dash
|
|
|
1086 |
var range = $.split(rangeAllowed);
|
|
|
1087 |
// min or max
|
|
|
1088 |
var minmax = parseInt(rangeAllowed.substr(3), 10)
|
|
|
1089 |
// range ?
|
|
|
1090 |
if (range.length == 2 && (value < parseInt(range[0], 10) || value > parseInt(range[1], 10) )) {
|
|
|
1091 |
return [ "out", range[0], range[1] ];
|
|
|
1092 |
} // value is out of range
|
|
|
1093 |
else if (rangeAllowed.indexOf('min') === 0 && (value < minmax )) // min
|
|
|
1094 |
{
|
|
|
1095 |
return ["min", minmax];
|
|
|
1096 |
} // value is below min
|
|
|
1097 |
else if (rangeAllowed.indexOf('max') === 0 && (value > minmax )) // max
|
|
|
1098 |
{
|
|
|
1099 |
return ["max", minmax];
|
|
|
1100 |
} // value is above max
|
|
|
1101 |
// since no other returns executed, value is in allowed range
|
|
|
1102 |
return [ "ok" ];
|
|
|
1103 |
},
|
|
|
1104 |
|
|
|
1105 |
|
|
|
1106 |
_numSuggestionElements: 0,
|
|
|
1107 |
_selectedSuggestion: null,
|
|
|
1108 |
_previousTypedVal: null,
|
|
|
1109 |
|
|
|
1110 |
/**
|
|
|
1111 |
* Utility function that can be used to create plugins that gives
|
|
|
1112 |
* suggestions when inputs is typed into
|
|
|
1113 |
* @param {jQuery} $elem
|
|
|
1114 |
* @param {Array} suggestions
|
|
|
1115 |
* @param {Object} settings - Optional
|
|
|
1116 |
* @return {jQuery}
|
|
|
1117 |
*/
|
|
|
1118 |
suggest: function ($elem, suggestions, settings) {
|
|
|
1119 |
var conf = {
|
|
|
1120 |
css: {
|
|
|
1121 |
maxHeight: '150px',
|
|
|
1122 |
background: '#FFF',
|
|
|
1123 |
lineHeight: '150%',
|
|
|
1124 |
textDecoration: 'underline',
|
|
|
1125 |
overflowX: 'hidden',
|
|
|
1126 |
overflowY: 'auto',
|
|
|
1127 |
border: '#CCC solid 1px',
|
|
|
1128 |
borderTop: 'none',
|
|
|
1129 |
cursor: 'pointer'
|
|
|
1130 |
},
|
|
|
1131 |
activeSuggestionCSS: {
|
|
|
1132 |
background: '#E9E9E9'
|
|
|
1133 |
}
|
|
|
1134 |
},
|
|
|
1135 |
setSuggsetionPosition = function ($suggestionContainer, $input) {
|
|
|
1136 |
var offset = $input.offset();
|
|
|
1137 |
$suggestionContainer.css({
|
|
|
1138 |
width: $input.outerWidth(),
|
|
|
1139 |
left: offset.left + 'px',
|
|
|
1140 |
top: (offset.top + $input.outerHeight()) + 'px'
|
|
|
1141 |
});
|
|
|
1142 |
};
|
|
|
1143 |
|
|
|
1144 |
if (settings)
|
|
|
1145 |
$.extend(conf, settings);
|
|
|
1146 |
|
|
|
1147 |
conf.css['position'] = 'absolute';
|
|
|
1148 |
conf.css['z-index'] = 9999;
|
|
|
1149 |
$elem.attr('autocomplete', 'off');
|
|
|
1150 |
|
|
|
1151 |
if (this._numSuggestionElements === 0) {
|
|
|
1152 |
// Re-position suggestion container if window size changes
|
|
|
1153 |
$window.bind('resize', function () {
|
|
|
1154 |
$('.jquery-form-suggestions').each(function () {
|
|
|
1155 |
var $container = $(this),
|
|
|
1156 |
suggestID = $container.attr('data-suggest-container');
|
|
|
1157 |
setSuggsetionPosition($container, $('.suggestions-' + suggestID).eq(0));
|
|
|
1158 |
});
|
|
|
1159 |
});
|
|
|
1160 |
}
|
|
|
1161 |
|
|
|
1162 |
this._numSuggestionElements++;
|
|
|
1163 |
|
|
|
1164 |
var onSelectSuggestion = function ($el) {
|
|
|
1165 |
var suggestionId = $el.valAttr('suggestion-nr');
|
|
|
1166 |
$.formUtils._selectedSuggestion = null;
|
|
|
1167 |
$.formUtils._previousTypedVal = null;
|
|
|
1168 |
$('.jquery-form-suggestion-' + suggestionId).fadeOut('fast');
|
|
|
1169 |
};
|
|
|
1170 |
|
|
|
1171 |
$elem
|
|
|
1172 |
.data('suggestions', suggestions)
|
|
|
1173 |
.valAttr('suggestion-nr', this._numSuggestionElements)
|
|
|
1174 |
.unbind('focus.suggest')
|
|
|
1175 |
.bind('focus.suggest', function () {
|
|
|
1176 |
$(this).trigger('keyup');
|
|
|
1177 |
$.formUtils._selectedSuggestion = null;
|
|
|
1178 |
})
|
|
|
1179 |
.unbind('keyup.suggest')
|
|
|
1180 |
.bind('keyup.suggest', function () {
|
|
|
1181 |
var $input = $(this),
|
|
|
1182 |
foundSuggestions = [],
|
|
|
1183 |
val = $.trim($input.val()).toLocaleLowerCase();
|
|
|
1184 |
|
|
|
1185 |
if (val == $.formUtils._previousTypedVal) {
|
|
|
1186 |
return;
|
|
|
1187 |
}
|
|
|
1188 |
else {
|
|
|
1189 |
$.formUtils._previousTypedVal = val;
|
|
|
1190 |
}
|
|
|
1191 |
|
|
|
1192 |
var hasTypedSuggestion = false,
|
|
|
1193 |
suggestionId = $input.valAttr('suggestion-nr'),
|
|
|
1194 |
$suggestionContainer = $('.jquery-form-suggestion-' + suggestionId);
|
|
|
1195 |
|
|
|
1196 |
$suggestionContainer.scrollTop(0);
|
|
|
1197 |
|
|
|
1198 |
// Find the right suggestions
|
|
|
1199 |
if (val != '') {
|
|
|
1200 |
var findPartial = val.length > 2;
|
|
|
1201 |
$.each($input.data('suggestions'), function (i, suggestion) {
|
|
|
1202 |
var lowerCaseVal = suggestion.toLocaleLowerCase();
|
|
|
1203 |
if (lowerCaseVal == val) {
|
|
|
1204 |
foundSuggestions.push('<strong>' + suggestion + '</strong>');
|
|
|
1205 |
hasTypedSuggestion = true;
|
|
|
1206 |
return false;
|
|
|
1207 |
} else if (lowerCaseVal.indexOf(val) === 0 || (findPartial && lowerCaseVal.indexOf(val) > -1)) {
|
|
|
1208 |
foundSuggestions.push(suggestion.replace(new RegExp(val, 'gi'), '<strong>$&</strong>'));
|
|
|
1209 |
}
|
|
|
1210 |
});
|
|
|
1211 |
}
|
|
|
1212 |
|
|
|
1213 |
// Hide suggestion container
|
|
|
1214 |
if (hasTypedSuggestion || (foundSuggestions.length == 0 && $suggestionContainer.length > 0)) {
|
|
|
1215 |
$suggestionContainer.hide();
|
|
|
1216 |
}
|
|
|
1217 |
|
|
|
1218 |
// Create suggestion container if not already exists
|
|
|
1219 |
else if (foundSuggestions.length > 0 && $suggestionContainer.length == 0) {
|
|
|
1220 |
$suggestionContainer = $('<div></div>').css(conf.css).appendTo('body');
|
|
|
1221 |
$elem.addClass('suggestions-' + suggestionId);
|
|
|
1222 |
$suggestionContainer
|
|
|
1223 |
.attr('data-suggest-container', suggestionId)
|
|
|
1224 |
.addClass('jquery-form-suggestions')
|
|
|
1225 |
.addClass('jquery-form-suggestion-' + suggestionId);
|
|
|
1226 |
}
|
|
|
1227 |
|
|
|
1228 |
// Show hidden container
|
|
|
1229 |
else if (foundSuggestions.length > 0 && !$suggestionContainer.is(':visible')) {
|
|
|
1230 |
$suggestionContainer.show();
|
|
|
1231 |
}
|
|
|
1232 |
|
|
|
1233 |
// add suggestions
|
|
|
1234 |
if (foundSuggestions.length > 0 && val.length != foundSuggestions[0].length) {
|
|
|
1235 |
|
|
|
1236 |
// put container in place every time, just in case
|
|
|
1237 |
setSuggsetionPosition($suggestionContainer, $input);
|
|
|
1238 |
|
|
|
1239 |
// Add suggestions HTML to container
|
|
|
1240 |
$suggestionContainer.html('');
|
|
|
1241 |
$.each(foundSuggestions, function (i, text) {
|
|
|
1242 |
$('<div></div>')
|
|
|
1243 |
.append(text)
|
|
|
1244 |
.css({
|
|
|
1245 |
overflow: 'hidden',
|
|
|
1246 |
textOverflow: 'ellipsis',
|
|
|
1247 |
whiteSpace: 'nowrap',
|
|
|
1248 |
padding: '5px'
|
|
|
1249 |
})
|
|
|
1250 |
.addClass('form-suggest-element')
|
|
|
1251 |
.appendTo($suggestionContainer)
|
|
|
1252 |
.click(function () {
|
|
|
1253 |
$input.focus();
|
|
|
1254 |
$input.val($(this).text());
|
|
|
1255 |
onSelectSuggestion($input);
|
|
|
1256 |
});
|
|
|
1257 |
});
|
|
|
1258 |
}
|
|
|
1259 |
})
|
|
|
1260 |
.unbind('keydown.validation')
|
|
|
1261 |
.bind('keydown.validation', function (e) {
|
|
|
1262 |
var code = (e.keyCode ? e.keyCode : e.which),
|
|
|
1263 |
suggestionId,
|
|
|
1264 |
$suggestionContainer,
|
|
|
1265 |
$input = $(this);
|
|
|
1266 |
|
|
|
1267 |
if (code == 13 && $.formUtils._selectedSuggestion !== null) {
|
|
|
1268 |
suggestionId = $input.valAttr('suggestion-nr');
|
|
|
1269 |
$suggestionContainer = $('.jquery-form-suggestion-' + suggestionId);
|
|
|
1270 |
if ($suggestionContainer.length > 0) {
|
|
|
1271 |
var newText = $suggestionContainer.find('div').eq($.formUtils._selectedSuggestion).text();
|
|
|
1272 |
$input.val(newText);
|
|
|
1273 |
onSelectSuggestion($input);
|
|
|
1274 |
e.preventDefault();
|
|
|
1275 |
}
|
|
|
1276 |
}
|
|
|
1277 |
else {
|
|
|
1278 |
suggestionId = $input.valAttr('suggestion-nr');
|
|
|
1279 |
$suggestionContainer = $('.jquery-form-suggestion-' + suggestionId);
|
|
|
1280 |
var $suggestions = $suggestionContainer.children();
|
|
|
1281 |
if ($suggestions.length > 0 && $.inArray(code, [38, 40]) > -1) {
|
|
|
1282 |
if (code == 38) { // key up
|
|
|
1283 |
if ($.formUtils._selectedSuggestion === null)
|
|
|
1284 |
$.formUtils._selectedSuggestion = $suggestions.length - 1;
|
|
|
1285 |
else
|
|
|
1286 |
$.formUtils._selectedSuggestion--;
|
|
|
1287 |
if ($.formUtils._selectedSuggestion < 0)
|
|
|
1288 |
$.formUtils._selectedSuggestion = $suggestions.length - 1;
|
|
|
1289 |
}
|
|
|
1290 |
else if (code == 40) { // key down
|
|
|
1291 |
if ($.formUtils._selectedSuggestion === null)
|
|
|
1292 |
$.formUtils._selectedSuggestion = 0;
|
|
|
1293 |
else
|
|
|
1294 |
$.formUtils._selectedSuggestion++;
|
|
|
1295 |
if ($.formUtils._selectedSuggestion > ($suggestions.length - 1))
|
|
|
1296 |
$.formUtils._selectedSuggestion = 0;
|
|
|
1297 |
|
|
|
1298 |
}
|
|
|
1299 |
|
|
|
1300 |
// Scroll in suggestion window
|
|
|
1301 |
var containerInnerHeight = $suggestionContainer.innerHeight(),
|
|
|
1302 |
containerScrollTop = $suggestionContainer.scrollTop(),
|
|
|
1303 |
suggestionHeight = $suggestionContainer.children().eq(0).outerHeight(),
|
|
|
1304 |
activeSuggestionPosY = suggestionHeight * ($.formUtils._selectedSuggestion);
|
|
|
1305 |
|
|
|
1306 |
if (activeSuggestionPosY < containerScrollTop || activeSuggestionPosY > (containerScrollTop + containerInnerHeight)) {
|
|
|
1307 |
$suggestionContainer.scrollTop(activeSuggestionPosY);
|
|
|
1308 |
}
|
|
|
1309 |
|
|
|
1310 |
$suggestions
|
|
|
1311 |
.removeClass('active-suggestion')
|
|
|
1312 |
.css('background', 'none')
|
|
|
1313 |
.eq($.formUtils._selectedSuggestion)
|
|
|
1314 |
.addClass('active-suggestion')
|
|
|
1315 |
.css(conf.activeSuggestionCSS);
|
|
|
1316 |
|
|
|
1317 |
e.preventDefault();
|
|
|
1318 |
return false;
|
|
|
1319 |
}
|
|
|
1320 |
}
|
|
|
1321 |
})
|
|
|
1322 |
.unbind('blur.suggest')
|
|
|
1323 |
.bind('blur.suggest', function () {
|
|
|
1324 |
onSelectSuggestion($(this));
|
|
|
1325 |
});
|
|
|
1326 |
|
|
|
1327 |
return $elem;
|
|
|
1328 |
},
|
|
|
1329 |
|
|
|
1330 |
/**
|
|
|
1331 |
* Error dialogs
|
|
|
1332 |
*
|
|
|
1333 |
* @var {Object}
|
|
|
1334 |
*/
|
|
|
1335 |
LANG: {
|
|
|
1336 |
errorTitle: 'Form submission failed!',
|
|
|
1337 |
requiredFields: 'You have not answered all required fields',
|
|
|
1338 |
badTime: 'You have not given a correct time',
|
|
|
1339 |
badEmail: 'You have not given a correct e-mail address',
|
|
|
1340 |
badTelephone: 'You have not given a correct phone number',
|
|
|
1341 |
badSecurityAnswer: 'You have not given a correct answer to the security question',
|
|
|
1342 |
badDate: 'You have not given a correct date',
|
|
|
1343 |
lengthBadStart: 'The input value must be between ',
|
|
|
1344 |
lengthBadEnd: ' characters',
|
|
|
1345 |
lengthTooLongStart: 'The input value is longer than ',
|
|
|
1346 |
lengthTooShortStart: 'The input value is shorter than ',
|
|
|
1347 |
notConfirmed: 'Input values could not be confirmed',
|
|
|
1348 |
badDomain: 'Incorrect domain value',
|
|
|
1349 |
badUrl: 'The input value is not a correct URL',
|
|
|
1350 |
badCustomVal: 'The input value is incorrect',
|
|
|
1351 |
andSpaces: ' and spaces ',
|
|
|
1352 |
badInt: 'The input value was not a correct number',
|
|
|
1353 |
badSecurityNumber: 'Your social security number was incorrect',
|
|
|
1354 |
badUKVatAnswer: 'Incorrect UK VAT Number',
|
|
|
1355 |
badStrength: 'The password isn\'t strong enough',
|
|
|
1356 |
badNumberOfSelectedOptionsStart: 'You have to choose at least ',
|
|
|
1357 |
badNumberOfSelectedOptionsEnd: ' answers',
|
|
|
1358 |
badAlphaNumeric: 'The input value can only contain alphanumeric characters ',
|
|
|
1359 |
badAlphaNumericExtra: ' and ',
|
|
|
1360 |
wrongFileSize: 'The file you are trying to upload is too large (max %s)',
|
|
|
1361 |
wrongFileType: 'Only files of type %s is allowed',
|
|
|
1362 |
groupCheckedRangeStart: 'Please choose between ',
|
|
|
1363 |
groupCheckedTooFewStart: 'Please choose at least ',
|
|
|
1364 |
groupCheckedTooManyStart: 'Please choose a maximum of ',
|
|
|
1365 |
groupCheckedEnd: ' item(s)',
|
|
|
1366 |
badCreditCard: 'The credit card number is not correct',
|
|
|
1367 |
badCVV: 'The CVV number was not correct'
|
|
|
1368 |
}
|
|
|
1369 |
};
|
|
|
1370 |
|
|
|
1371 |
|
|
|
1372 |
/* * * * * * * * * * * * * * * * * * * * * *
|
|
|
1373 |
CORE VALIDATORS
|
|
|
1374 |
* * * * * * * * * * * * * * * * * * * * */
|
|
|
1375 |
|
|
|
1376 |
|
|
|
1377 |
/*
|
|
|
1378 |
* Validate email
|
|
|
1379 |
*/
|
|
|
1380 |
$.formUtils.addValidator({
|
|
|
1381 |
name: 'email',
|
|
|
1382 |
validatorFunction: function (email) {
|
|
|
1383 |
|
|
|
1384 |
var emailParts = email.toLowerCase().split('@');
|
|
|
1385 |
if (emailParts.length == 2) {
|
|
|
1386 |
return $.formUtils.validators.validate_domain.validatorFunction(emailParts[1]) && !(/[^\w\+\.\-]/.test(emailParts[0])) && emailParts[0].length > 0;
|
|
|
1387 |
}
|
|
|
1388 |
|
|
|
1389 |
return false;
|
|
|
1390 |
},
|
|
|
1391 |
errorMessage: '',
|
|
|
1392 |
errorMessageKey: 'badEmail'
|
|
|
1393 |
});
|
|
|
1394 |
|
|
|
1395 |
/*
|
|
|
1396 |
* Validate domain name
|
|
|
1397 |
*/
|
|
|
1398 |
$.formUtils.addValidator({
|
|
|
1399 |
name: 'domain',
|
|
|
1400 |
validatorFunction: function (val) {
|
|
|
1401 |
return val.length > 0 &&
|
|
|
1402 |
val.length <= 253 && // Including sub domains
|
|
|
1403 |
!(/[^a-zA-Z0-9]/.test(val.substr(-2))) && !(/[^a-zA-Z]/.test(val.substr(0, 1))) && !(/[^a-zA-Z0-9\.\-]/.test(val)) &&
|
|
|
1404 |
val.split('..').length == 1 &&
|
|
|
1405 |
val.split('.').length > 1;
|
|
|
1406 |
},
|
|
|
1407 |
errorMessage: '',
|
|
|
1408 |
errorMessageKey: 'badDomain'
|
|
|
1409 |
});
|
|
|
1410 |
|
|
|
1411 |
/*
|
|
|
1412 |
* Validate required
|
|
|
1413 |
*/
|
|
|
1414 |
$.formUtils.addValidator({
|
|
|
1415 |
name: 'required',
|
|
|
1416 |
validatorFunction: function (val, $el, config, language, $form) {
|
|
|
1417 |
switch ($el.attr('type')) {
|
|
|
1418 |
case 'checkbox':
|
|
|
1419 |
return $el.is(':checked');
|
|
|
1420 |
case 'radio':
|
|
|
1421 |
return $form.find('input[name="' + $el.attr('name') + '"]').filter(':checked').length > 0;
|
|
|
1422 |
default:
|
|
|
1423 |
return $.trim(val) !== '';
|
|
|
1424 |
}
|
|
|
1425 |
},
|
|
|
1426 |
errorMessage: '',
|
|
|
1427 |
errorMessageKey: 'requiredFields'
|
|
|
1428 |
});
|
|
|
1429 |
|
|
|
1430 |
/*
|
|
|
1431 |
* Validate length range
|
|
|
1432 |
*/
|
|
|
1433 |
$.formUtils.addValidator({
|
|
|
1434 |
name: 'length',
|
|
|
1435 |
validatorFunction: function (val, $el, conf, lang) {
|
|
|
1436 |
var lengthAllowed = $el.valAttr('length'),
|
|
|
1437 |
type = $el.attr('type');
|
|
|
1438 |
|
|
|
1439 |
if (lengthAllowed == undefined) {
|
|
|
1440 |
alert('Please add attribute "data-validation-length" to ' + $el[0].nodeName + ' named ' + $el.attr('name'));
|
|
|
1441 |
return true;
|
|
|
1442 |
}
|
|
|
1443 |
|
|
|
1444 |
// check if length is above min, below max or within range.
|
|
|
1445 |
var len = type == 'file' && $el.get(0).files !== undefined ? $el.get(0).files.length : val.length,
|
|
|
1446 |
lengthCheckResults = $.formUtils.numericRangeCheck(len, lengthAllowed),
|
|
|
1447 |
checkResult;
|
|
|
1448 |
|
|
|
1449 |
switch (lengthCheckResults[0]) { // outside of allowed range
|
|
|
1450 |
case "out":
|
|
|
1451 |
this.errorMessage = lang.lengthBadStart + lengthAllowed + lang.lengthBadEnd;
|
|
|
1452 |
checkResult = false;
|
|
|
1453 |
break;
|
|
|
1454 |
// too short
|
|
|
1455 |
case "min":
|
|
|
1456 |
this.errorMessage = lang.lengthTooShortStart + lengthCheckResults[1] + lang.lengthBadEnd;
|
|
|
1457 |
checkResult = false;
|
|
|
1458 |
break;
|
|
|
1459 |
// too long
|
|
|
1460 |
case "max":
|
|
|
1461 |
this.errorMessage = lang.lengthTooLongStart + lengthCheckResults[1] + lang.lengthBadEnd;
|
|
|
1462 |
checkResult = false;
|
|
|
1463 |
break;
|
|
|
1464 |
// ok
|
|
|
1465 |
default:
|
|
|
1466 |
checkResult = true;
|
|
|
1467 |
}
|
|
|
1468 |
|
|
|
1469 |
return checkResult;
|
|
|
1470 |
},
|
|
|
1471 |
errorMessage: '',
|
|
|
1472 |
errorMessageKey: ''
|
|
|
1473 |
});
|
|
|
1474 |
|
|
|
1475 |
/*
|
|
|
1476 |
* Validate url
|
|
|
1477 |
*/
|
|
|
1478 |
$.formUtils.addValidator({
|
|
|
1479 |
name: 'url',
|
|
|
1480 |
validatorFunction: function (url) {
|
|
|
1481 |
// written by Scott Gonzalez: http://projects.scottsplayground.com/iri/
|
|
|
1482 |
// - Victor Jonsson added support for arrays in the url ?arg[]=sdfsdf
|
|
|
1483 |
// - General improvements made by Stéphane Moureau <https://github.com/TraderStf>
|
|
|
1484 |
var urlFilter = /^(https?|ftp):\/\/((((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])(\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])(\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/(((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|\[|\]|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#(((\w|-|\.|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i;
|
|
|
1485 |
if (urlFilter.test(url)) {
|
|
|
1486 |
var domain = url.split('://')[1],
|
|
|
1487 |
domainSlashPos = domain.indexOf('/');
|
|
|
1488 |
|
|
|
1489 |
if (domainSlashPos > -1)
|
|
|
1490 |
domain = domain.substr(0, domainSlashPos);
|
|
|
1491 |
|
|
|
1492 |
return $.formUtils.validators.validate_domain.validatorFunction(domain); // todo: add support for IP-addresses
|
|
|
1493 |
}
|
|
|
1494 |
return false;
|
|
|
1495 |
},
|
|
|
1496 |
errorMessage: '',
|
|
|
1497 |
errorMessageKey: 'badUrl'
|
|
|
1498 |
});
|
|
|
1499 |
|
|
|
1500 |
/*
|
|
|
1501 |
* Validate number (floating or integer)
|
|
|
1502 |
*/
|
|
|
1503 |
$.formUtils.addValidator({
|
|
|
1504 |
name: 'number',
|
|
|
1505 |
validatorFunction: function (val, $el, conf) {
|
|
|
1506 |
if (val !== '') {
|
|
|
1507 |
var allowing = $el.valAttr('allowing') || '',
|
|
|
1508 |
decimalSeparator = $el.valAttr('decimal-separator') || conf.decimalSeparator,
|
|
|
1509 |
allowsRange = false,
|
|
|
1510 |
begin, end,
|
|
|
1511 |
steps = $el.valAttr('step') || '',
|
|
|
1512 |
allowsSteps = false;
|
|
|
1513 |
|
|
|
1514 |
if (allowing.indexOf('number') == -1)
|
|
|
1515 |
allowing += ',number';
|
|
|
1516 |
|
|
|
1517 |
if (allowing.indexOf('negative') == -1 && val.indexOf('-') === 0) {
|
|
|
1518 |
return false;
|
|
|
1519 |
}
|
|
|
1520 |
|
|
|
1521 |
if (allowing.indexOf('range') > -1) {
|
|
|
1522 |
begin = parseFloat(allowing.substring(allowing.indexOf("[") + 1, allowing.indexOf(";")));
|
|
|
1523 |
end = parseFloat(allowing.substring(allowing.indexOf(";") + 1, allowing.indexOf("]")));
|
|
|
1524 |
allowsRange = true;
|
|
|
1525 |
}
|
|
|
1526 |
|
|
|
1527 |
if (steps != "")
|
|
|
1528 |
allowsSteps = true;
|
|
|
1529 |
|
|
|
1530 |
if (decimalSeparator == ',') {
|
|
|
1531 |
if (val.indexOf('.') > -1) {
|
|
|
1532 |
return false;
|
|
|
1533 |
}
|
|
|
1534 |
// Fix for checking range with floats using ,
|
|
|
1535 |
val = val.replace(',', '.');
|
|
|
1536 |
}
|
|
|
1537 |
|
|
|
1538 |
if (allowing.indexOf('number') > -1 && val.replace(/[0-9-]/g, '') === '' && (!allowsRange || (val >= begin && val <= end)) && (!allowsSteps || (val % steps == 0))) {
|
|
|
1539 |
return true;
|
|
|
1540 |
}
|
|
|
1541 |
if (allowing.indexOf('float') > -1 && val.match(new RegExp('^([0-9-]+)\\.([0-9]+)$')) !== null && (!allowsRange || (val >= begin && val <= end)) && (!allowsSteps || (val % steps == 0))) {
|
|
|
1542 |
return true;
|
|
|
1543 |
}
|
|
|
1544 |
}
|
|
|
1545 |
return false;
|
|
|
1546 |
},
|
|
|
1547 |
errorMessage: '',
|
|
|
1548 |
errorMessageKey: 'badInt'
|
|
|
1549 |
});
|
|
|
1550 |
|
|
|
1551 |
/*
|
|
|
1552 |
* Validate alpha numeric
|
|
|
1553 |
*/
|
|
|
1554 |
$.formUtils.addValidator({
|
|
|
1555 |
name: 'alphanumeric',
|
|
|
1556 |
validatorFunction: function (val, $el, conf, language) {
|
|
|
1557 |
var patternStart = '^([a-zA-Z0-9',
|
|
|
1558 |
patternEnd = ']+)$',
|
|
|
1559 |
additionalChars = $el.valAttr('allowing'),
|
|
|
1560 |
pattern = '';
|
|
|
1561 |
|
|
|
1562 |
if (additionalChars) {
|
|
|
1563 |
pattern = patternStart + additionalChars + patternEnd;
|
|
|
1564 |
var extra = additionalChars.replace(/\\/g, '');
|
|
|
1565 |
if (extra.indexOf(' ') > -1) {
|
|
|
1566 |
extra = extra.replace(' ', '');
|
|
|
1567 |
extra += language.andSpaces || $.formUtils.LANG.andSpaces;
|
|
|
1568 |
}
|
|
|
1569 |
this.errorMessage = language.badAlphaNumeric + language.badAlphaNumericExtra + extra;
|
|
|
1570 |
} else {
|
|
|
1571 |
pattern = patternStart + patternEnd;
|
|
|
1572 |
this.errorMessage = language.badAlphaNumeric;
|
|
|
1573 |
}
|
|
|
1574 |
|
|
|
1575 |
return new RegExp(pattern).test(val);
|
|
|
1576 |
},
|
|
|
1577 |
errorMessage: '',
|
|
|
1578 |
errorMessageKey: ''
|
|
|
1579 |
});
|
|
|
1580 |
|
|
|
1581 |
/*
|
|
|
1582 |
* Validate against regexp
|
|
|
1583 |
*/
|
|
|
1584 |
$.formUtils.addValidator({
|
|
|
1585 |
name: 'custom',
|
|
|
1586 |
validatorFunction: function (val, $el, conf) {
|
|
|
1587 |
var regexp = new RegExp($el.valAttr('regexp'));
|
|
|
1588 |
return regexp.test(val);
|
|
|
1589 |
},
|
|
|
1590 |
errorMessage: '',
|
|
|
1591 |
errorMessageKey: 'badCustomVal'
|
|
|
1592 |
});
|
|
|
1593 |
|
|
|
1594 |
/*
|
|
|
1595 |
* Validate date
|
|
|
1596 |
*/
|
|
|
1597 |
$.formUtils.addValidator({
|
|
|
1598 |
name: 'date',
|
|
|
1599 |
validatorFunction: function (date, $el, conf) {
|
|
|
1600 |
var dateFormat = $el.valAttr('format') || conf.dateFormat || 'yyyy-mm-dd';
|
|
|
1601 |
return $.formUtils.parseDate(date, dateFormat) !== false;
|
|
|
1602 |
},
|
|
|
1603 |
errorMessage: '',
|
|
|
1604 |
errorMessageKey: 'badDate'
|
|
|
1605 |
});
|
|
|
1606 |
|
|
|
1607 |
|
|
|
1608 |
/*
|
|
|
1609 |
* Validate group of checkboxes, validate qty required is checked
|
|
|
1610 |
* written by Steve Wasiura : http://stevewasiura.waztech.com
|
|
|
1611 |
* element attrs
|
|
|
1612 |
* data-validation="checkbox_group"
|
|
|
1613 |
* data-validation-qty="1-2" // min 1 max 2
|
|
|
1614 |
* data-validation-error-msg="chose min 1, max of 2 checkboxes"
|
|
|
1615 |
*/
|
|
|
1616 |
$.formUtils.addValidator({
|
|
|
1617 |
name: 'checkbox_group',
|
|
|
1618 |
validatorFunction: function (val, $el, conf, lang, $form) {
|
|
|
1619 |
// preset return var
|
|
|
1620 |
var checkResult = true,
|
|
|
1621 |
// get name of element. since it is a checkbox group, all checkboxes will have same name
|
|
|
1622 |
elname = $el.attr('name'),
|
|
|
1623 |
// get checkboxes and count the checked ones
|
|
|
1624 |
$checkBoxes = $("input[type=checkbox][name^='" + elname + "']", $form),
|
|
|
1625 |
checkedCount = $checkBoxes.filter(':checked').length,
|
|
|
1626 |
// get el attr that specs qty required / allowed
|
|
|
1627 |
qtyAllowed = $el.valAttr('qty');
|
|
|
1628 |
|
|
|
1629 |
if (qtyAllowed == undefined) {
|
|
|
1630 |
var elementType = $el.get(0).nodeName;
|
|
|
1631 |
alert('Attribute "data-validation-qty" is missing from ' + elementType + ' named ' + $el.attr('name'));
|
|
|
1632 |
}
|
|
|
1633 |
|
|
|
1634 |
// call Utility function to check if count is above min, below max, within range etc.
|
|
|
1635 |
var qtyCheckResults = $.formUtils.numericRangeCheck(checkedCount, qtyAllowed);
|
|
|
1636 |
|
|
|
1637 |
// results will be array, [0]=result str, [1]=qty int
|
|
|
1638 |
switch (qtyCheckResults[0]) {
|
|
|
1639 |
// outside allowed range
|
|
|
1640 |
case "out":
|
|
|
1641 |
this.errorMessage = lang.groupCheckedRangeStart + qtyAllowed + lang.groupCheckedEnd;
|
|
|
1642 |
checkResult = false;
|
|
|
1643 |
break;
|
|
|
1644 |
// below min qty
|
|
|
1645 |
case "min":
|
|
|
1646 |
this.errorMessage = lang.groupCheckedTooFewStart + qtyCheckResults[1] + lang.groupCheckedEnd;
|
|
|
1647 |
checkResult = false;
|
|
|
1648 |
break;
|
|
|
1649 |
// above max qty
|
|
|
1650 |
case "max":
|
|
|
1651 |
this.errorMessage = lang.groupCheckedTooManyStart + qtyCheckResults[1] + lang.groupCheckedEnd;
|
|
|
1652 |
checkResult = false;
|
|
|
1653 |
break;
|
|
|
1654 |
// ok
|
|
|
1655 |
default:
|
|
|
1656 |
checkResult = true;
|
|
|
1657 |
}
|
|
|
1658 |
|
|
|
1659 |
if( !checkResult ) {
|
|
|
1660 |
var _triggerOnBlur = function() {
|
|
|
1661 |
$checkBoxes.unbind('click', _triggerOnBlur);
|
|
|
1662 |
$checkBoxes.filter('*[data-validation]').trigger('blur');
|
|
|
1663 |
};
|
|
|
1664 |
$checkBoxes.bind('click', _triggerOnBlur);
|
|
|
1665 |
}
|
|
|
1666 |
|
|
|
1667 |
return checkResult;
|
|
|
1668 |
}
|
|
|
1669 |
// errorMessage : '', // set above in switch statement
|
|
|
1670 |
// errorMessageKey: '' // not used
|
|
|
1671 |
});
|
|
|
1672 |
|
|
|
1673 |
})(jQuery);
|