This repository has been archived by the owner on Dec 14, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.js
520 lines (465 loc) · 18.9 KB
/
form.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
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
/**
* ACCESSIBLE Form Framework
* Easy-to-build accessible and user-friendly webforms
*
* Demo: http://www.wienfluss.net/form-framework
*
* Copyright (c) 2011 WIENFLUSS information.design.solutions KG
* For contributions take a look @ humans.txt
*
* Dual licensed under the MIT (MIT-LICENSE.txt)
* or GPL v3 (GPL-LICENSE.txt) licenses.
*
* 2011-08-15: Forked by @yatil from: http://code.google.com/p/wienfluss-form-framework to add basic HTML5 features
* 2011-08-15: Added basic HTML5 form elements support
*/
// self executing function to avoid global namespace conflicts
(function($) {
/*
** A wrapper for attaching the jQuery UI autocomplete feature
** Settings:
** * source (required): the data sourc: either an array, or string (=URL) (none)
** * delay: time in ms to wait after keystroke to set the query (0)
** * minLength: minimal number of characters to start query (0)
*/
$.fn.autosuggest = function(settings) {
var o = $.extend({
delay: 0,
minLength: 0
}, settings);
return this.each(function() {
var input = $(this);
input.autocomplete({
source: o.source,
delay: o.delay,
minLength: o.minLength
});
// open the autocomplete on focus when minLength:0
if ( o.minLength == 0 ) {
input.focus(function() {
if ( input.val() == '' ) input.autocomplete('search', '');
});
}
});
};
/*
** Form Enhancement
** add aria-required
** add form validation (inclucding aria-invalid) based on class names
** Settings: ( see right below for defaults )
** * FIELD_SELECTORS: Selector for input fields which to consider for all features ( errors, tooltips, datepickers, ... )
** * VALIDATION_SELECTORS: Selector for all fields which to consider for validation
** * BUBBLE_DELAY: Time in [ms] for how long error bubble is visible
** * RULES: Set of validation rules, each consisting of a message and validation function. Triggered through classnames that are the same as thr rule name.
*/
$.fn.enhanceForm = function(settings) {
var o = $.extend({
FIELD_SELECTORS: 'input[type=search], input[type=tel], input[type=url], input[type=email], input[type=datetime], input[type=date], input[type=month], input[type=week], input[type=time], input[type=datetime-local], input[type=number], input[type=range], input[type=color], input:text, input:password, input:file, input:radio, input:checkbox, textarea, select, fieldset.optiongroup',
VALIDATION_SELECTORS: 'input:text, input:password, input:file, input:checkbox, textarea, fieldset.optiongroup',
BUBBLE_DELAY: 4000,
RULES: {
'required': {
message: 'Pflichtfeld',
isValid: function(val) {
return val.length;
}
},
'email': {
message: 'Keine gültige E-Mail Adresse',
isValid: function(val) {
return ( val =='' || val.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) );
}
},
'datepicker': {
message: 'Datum ungültig',
isValid: function(val) {
return ( val == '' || val.match(/^[0-3]?[0-9]\.[01]?[0-9]\.[12][90][0-9][0-9]$/) );
}
},
'time': {
message: 'Keine gültige Zeit',
isValid: function(val) {
return ( val == '' || val.match(/^\d{1,2}:\d{2}$/) );
}
},
'password': {
message: 'Passwort nicht gülitg',
isValid: function(val) {
return ( val =='' || val.length > 5 );
}
},
'passwordRepeat': {
message: 'Passwörter stimmen nicht überein',
isValid: function(val) {
var firstField = this.closest('form').find('input.password:first');
return ( val == firstField.val() );
}
},
'radiogroup' : {
message: 'Es muss mindestens eine Option gewählt werden'
},
'numeric' : {
message: 'Der Wert des Feldes muss numerisch sein.',
isValid: function(val) {
return (val.length == 0 || val.match(/^[0-9+ ,:.\/*-]+$/));
}
},
'numericduty' : {
message: 'Der Wert des Feldes muss numerisch sein.',
isValid: function(val) {
return (val.length > 0 && val.match(/^[0-9+ ,:.\/*-]+$/));
}
},
'alphanumeric' : {
message: 'Der Wert des Feldes muss alphanumerisch sein.',
isValid: function(val) {
return (val.length == 0 || val.match(/^[a-zA-ZäöüÄÖÜß0-9+ ,.\/*-]+$/));
}
},
'alphabetic' : {
message: 'Der Wert des Feldes muss alphabetisch sein.',
isValid: function(val) {
return (val.length == 0 || val.match(/^[a-zA-ZäöüÄÖÜß+ ,.\/*-]+$/));
}
}
}
}, settings) ;
// HELPERS
$.fn.extend({
// add Errors to Error bubble
// call on input fields
addErrors: function() {
return this.each(function() {
var input = $(this),
errors = input.data('errors'),
bubble = input.next('.errorBubble').children('div'),
errorsHtml = ''
;
bubble.html('');
for ( var i=errors.length; i--; ) {
errorsHtml += '<p class="'+errors[i]+'_error" role="alert">'+o.RULES[errors[i]].message+'</p>';
}
$(errorsHtml).appendTo(bubble);
});
},
// call on Error bubble
hideBubble: function(withDelay) {
return this.each(function() {
var bubble = $(this);
if ( withDelay ) bubble.data('timeout', setTimeout(doHide, o.BUBBLE_DELAY));
else doHide();
function doHide() {
if ( bubble.is(':hidden') ) return;
bubble.hide('drop', {direction: 'up'}, 100);
}
});
},
// call on Error bubble
showBubble: function() {
return this.each(function() {
if ( $(this).is(':visible') ) {
clearTimeout($(this).data('timeout'));
return;
}
$(this).show('drop', {direction: 'up'}, 100);
});
},
// removes <strong> and <a> from the label and returns just the label text
// call on input fields
getLabeltext: function() {
return $(this).siblings('label').clone().remove().find('strong, a').remove().end().text();
},
// call on input fields
addTooltip: function() {
return this.each(function() {
var input = $(this);
if (! input.attr('title') ) return;
var text = input.attr('title');
input.data('tooltip', text).attr('aria-describedby', input.attr('id')+'_tooltip');
$('<div id="'+input.attr('id')+'_tooltip" class="tooltip" role="tooltip">'+text+'</div>').hide().insertBefore(input);
});
},
// call on input fields
showTooltip: function() {
return this.each(function() {
$(this).prev('.tooltip').fadeIn(200);
});
},
//call on input fields
hideTooltip: function() {
return this.each(function() {
$(this).prev('.tooltip').fadeOut(100);
});
}
});
function initErrors () {
$(o.VALIDATION_SELECTORS).each(function() {
var field = $(this),
errorPs = field.next().find('p'),
errors = []
;
for ( var i=errorPs.length; i--; ) {
errors.push($(errorPs[i]).attr('class').split('_')[0]);
}
if ( errors.length ) field.data('errors', errors);
});
}
return this.each(function(i) {
var form = $(this);
initErrors();
// add all tooltips
form.find(o.FIELD_SELECTORS).filter('.tooltip').addTooltip();
// add aria-required attribute
form.find(o.VALIDATION_SELECTORS).filter('.required').attr('aria-required', 'true');
form.find(o.VALIDATION_SELECTORS).filter('[required]').attr('aria-required', 'true');
// add aria-radiogroup
form.find(o.VALIDATION_SELECTORS).filter('.radiogroup').attr('role', 'aria-radiogroup');
// init all datepickers
if ( $.datepicker ) {
form.find('input.datepicker').datepicker({
onSelect: function(selectedDate) {
$(this).trigger('validate', ['datepicker']);
}
})
// set special options on bithday datepickers
.filter('.birthday').datepicker( 'option', {
changeMonth: true,
changeYear: true,
yearRange: '1900:c',
defaultDate: '-50y'
})
// hide all datepickers
.end().datepicker('widget').hide()
;
}
// create all context help dialogs
var dialogs = [];
form.find('a.help').each(function(i) {
var trigger = $(this),
ajaxUrl = trigger.attr('href'),
dialogTitle, dialogContent
;
// Get the dialog title and content via ajax
$.ajax({
url: ajaxUrl,
dataType: 'json',
success: function(data) {
dialogTitle = data.title;
dialogContent = data.content;
initDialogs();
},
error: function() {
trigger.remove();
}
});
function initDialogs () {
dialogs[i] = $('<div></div>')
.html(dialogContent)
.dialog({
title: dialogTitle,
autoOpen: false,
open: function() {
var dialog = $(this),
dialogContainer = dialog.dialog('widget'),
trigger_pos = trigger.offset(),
x = trigger_pos.left - $(document).scrollLeft() - dialogContainer.outerWidth()/2,
y = trigger_pos.top - $(document).scrollTop() - dialogContainer.outerHeight()
;
dialog.dialog('option', 'position', [x,y]);
},
close: function() {
trigger.focus();
}
});
trigger.click(function() {
var dialog = dialogs[i];
if ( dialog.dialog('isOpen') ) dialog.dialog('close');
else {
for ( var j=dialogs.length; j--; ) {
if ( dialogs[j].dialog('isOpen') ) dialogs[j].dialog('close');
}
dialog.dialog('open');
}
return false;
});
}
});
form
/******* general validater *******/
.bind('validate', function(event, types, isSubmit) {
var target = $(event.target),
errors = [];
for ( var i=types.length; i--; ) {
var type = types[i];
if ( type == '' || o.RULES[type] === undefined ) continue;
switch( target.attr('type') ) {
case 'checkbox':
if( !target.is(':checked') ) {errors.push(type);}
break;
case 'fieldset':
if( target.find('input:checked').length == 0 ) { errors.push(type);}
break;
default:
// If the field is not valid add the error to our errors array
if (! o.RULES[type].isValid.call(target, target.val()) ) errors.push(type);
}
}
if ( errors.length ) {
target.trigger('error', [errors, isSubmit]);
} else {
target.trigger('valid');
}
})
/******* valid *******/
.bind('valid', function(event) {
var target = $(event.target),
hadErrors = target.data('errors')
;
if (! hadErrors ) return;
target.next('.errorBubble').remove();
target
.removeAttr('aria-invalid').removeAttr('aria-labelledby')
.removeData('errors')
.parent().removeClass('wrong');
})
/******* error *******/
.bind('error', function(event, errors, isSubmit) {
var target = $(event.target),
target_id = target.attr('id'),
hadErrors = target.data('errors'),
errorBubble = target.next('.errorBubble')
;
if (! hadErrors ) {
if ( target.is('textarea') ) target.parent().addClass('textarea');
target.attr({'aria-invalid': 'true', 'aria-labelledby': target_id+'_error'})
.parent().addClass('wrong')
;
errorBubble = $('<div class="errorBubble" id="'+target_id+'_error"><div></div></div>')
.hide()
.insertAfter(target)
;
if( target.is('fieldset') ) {errorBubble.addClass('errorBubbleFieldset');}
if( target.is('input:checkbox') ) {errorBubble.addClass('errorBubbleCheckbox');}
} else if ( errors.equals(hadErrors) && !isSubmit ) {
errorBubble.hideBubble();
return;
}
target.data('errors', errors).addErrors();
errorBubble
.showBubble()
.hideBubble(true);
})
/******* create, delete or update the Error Summary *******/
.bind('errorSummary', function(event, valid) {
var form = $(this),
summary = form.find('div.errorSummary'),
hasSummary = summary.length,
summaryOnBottom = hasSummary && summary.next('div.submit').length,
validationFields = $(this).find(o.VALIDATION_SELECTORS)
;
if ( valid ) {
if ( hasSummary ) summary.remove();
return;
}
if (! summaryOnBottom ) {
summary.slideUp(300, function() {$(this).remove();});
var summary = $('<div class="errorSummary"><div><h2>Fehler! <span>Folgende Fehler sind beim ausfüllen aufgetreten:</span></h2><ul></ul></div></div>')
.insertBefore(form.find('div.submit'))
.fadeTo(0,0).hide()
;
}
var list = summary.find('ul').html(''),
itemsHtml = ''
;
for ( var i=0,len=validationFields.length; i<len; i++ ) {
var inputfield = $(validationFields[i]),
errors = inputfield.data('errors')
;
if (! errors ) continue;
for ( var j=errors.length; j--; ) {
switch( inputfield.get(0).tagName ) {
case 'FIELDSET':
var legendtext = inputfield.find('legend').find('strong, a').remove().end().text(),
errortext = o.RULES['radiogroup'].message,
first_radio_id = inputfield.find('input:radio:first').attr('id');
itemsHtml += '<li><a href="#'+first_radio_id+'">'+legendtext+': '+errortext+'</a></li>';
break;
default : itemsHtml += '<li><a href="#'+inputfield.attr('id')+'">'+inputfield.getLabeltext()+': '+o.RULES[errors[j]].message+'</a></li>';
}
}
}
$(itemsHtml).appendTo(list);
// focus field on click
list.click(function(event) {
var target = $(event.target);
if ( target.is('a') ) $('#'+target.attr('href').split('#')[1]).focus();
return false;
});
if (! summaryOnBottom ) summary.slideDown(300).fadeTo(300,1);
});
// ------------------------------------ //
// Now let's react to the users inputs //
// ------------------------------------ //
form
/******** on focus of the fields ********/
.focusin(function(event) {
var target = $(event.target);
if ( target.is(o.FIELD_SELECTORS) || target.is('a.help') ) target.closest('.field').addClass('fieldFocused')
.closest('.section').addClass('sectionFocused')
.closest('form').addClass('isFocused');
// if we have a tooltip show it
if ( target.data('tooltip') ) target.showTooltip();
// if we have errors show the errorBubble
if ( target.data('errors') ) target.next('.errorBubble').showBubble();
})
/******** on blur of the fields ********/
.focusout(function(event) {
var target = $(event.target);
if ( target.is(o.FIELD_SELECTORS) || target.is('a.help') ) target.closest('.field').removeClass('fieldFocused')
.closest('.section').removeClass('sectionFocused')
.closest('form').removeClass('isFocused');
if (! target.is(o.VALIDATION_SELECTORS) ) return;
if (! target.attr('class').length ) return;
// if we have a tooltip hide it
if ( target.data('tooltip') ) target.hideTooltip();
var classes = target.attr('class').split(' ');
target.trigger('validate', [classes]);
})
/******** on submit of the form ********/
.submit(function(event) {
var validationFields = $(this).find(o.VALIDATION_SELECTORS),
valid = true
;
validationFields.each(function() {
if (! $(this).attr("class").length ) return true;
var classes = $(this).attr('class').split(' '),
returned = $(this).trigger('validate', [classes, true])
;
if ( returned.data('errors') ) valid = false;
});
$(this).trigger('errorSummary', valid);
if ( valid ) {
if ( o.ajaxSubmit ) $(this).trigger(o.ajaxSubmit);
else return true;
}
return false;
})
$(window).unload(function() {
form.unbind();
});
});
};
// Array Helper
// compares if two array are equal
Array.prototype.equals = function(arr) {
if (! arr ) return false;
if (this.length != arr.length) return false;
for (var i=arr.length; i--; ) {
if (this[i].compare) {
if (!this[i].compare(arr[i])) return false;
}
if (this[i] !== arr[i]) return false;
}
return true;
};
})(jQuery);