Valid HTML test
[weblabels.fsf.org.git] / defectivebydesign.org / 20130319 / files / crm.fsf.org / jquery.validate.js
... / ...
CommitLineData
1/**
2 * jQuery Validation Plugin 1.8.0
3 *
4 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
5 * http://docs.jquery.com/Plugins/Validation
6 *
7 * Copyright (c) 2006 - 2011 Jörn Zaefferer
8 *
9 * Dual licensed under the MIT and GPL licenses:
10 * http://www.opensource.org/licenses/mit-license.php
11 * http://www.gnu.org/licenses/gpl.html
12 */
13
14(function($) {
15
16$.extend($.fn, {
17 // http://docs.jquery.com/Plugins/Validation/validate
18 validate: function( options ) {
19
20 // if nothing is selected, return nothing; can't chain anyway
21 if (!this.length) {
22 options && options.debug && window.console && console.warn( "nothing selected, can't validate, returning nothing" );
23 return;
24 }
25
26 // check if a validator for this form was already created
27 var validator = $.data(this[0], 'validator');
28 if ( validator ) {
29 return validator;
30 }
31
32 validator = new $.validator( options, this[0] );
33 $.data(this[0], 'validator', validator);
34
35 if ( validator.settings.onsubmit ) {
36
37 // allow suppresing validation by adding a cancel class to the submit button
38 this.find("input, button").filter(".cancel").click(function() {
39 validator.cancelSubmit = true;
40 });
41
42 // when a submitHandler is used, capture the submitting button
43 if (validator.settings.submitHandler) {
44 this.find("input, button").filter(":submit").click(function() {
45 validator.submitButton = this;
46 });
47 }
48
49 // validate the form on submit
50 this.submit( function( event ) {
51 if ( validator.settings.debug )
52 // prevent form submit to be able to see console output
53 event.preventDefault();
54
55 function handle() {
56 if ( validator.settings.submitHandler ) {
57 if (validator.submitButton) {
58 // insert a hidden input as a replacement for the missing submit button
59 var hidden = $("<input type='hidden'/>").attr("name", validator.submitButton.name).val(validator.submitButton.value).appendTo(validator.currentForm);
60 }
61 validator.settings.submitHandler.call( validator, validator.currentForm );
62 if (validator.submitButton) {
63 // and clean up afterwards; thanks to no-block-scope, hidden can be referenced
64 hidden.remove();
65 }
66 return false;
67 }
68 return true;
69 }
70
71 // prevent submit for invalid forms or custom submit handlers
72 if ( validator.cancelSubmit ) {
73 validator.cancelSubmit = false;
74 return handle();
75 }
76 if ( validator.form() ) {
77 if ( validator.pendingRequest ) {
78 validator.formSubmitted = true;
79 return false;
80 }
81 return handle();
82 } else {
83 validator.focusInvalid();
84 return false;
85 }
86 });
87 }
88
89 return validator;
90 },
91 // http://docs.jquery.com/Plugins/Validation/valid
92 valid: function() {
93 if ( $(this[0]).is('form')) {
94 return this.validate().form();
95 } else {
96 var valid = true;
97 var validator = $(this[0].form).validate();
98 this.each(function() {
99 valid &= validator.element(this);
100 });
101 return valid;
102 }
103 },
104 // attributes: space seperated list of attributes to retrieve and remove
105 removeAttrs: function(attributes) {
106 var result = {},
107 $element = this;
108 $.each(attributes.split(/\s/), function(index, value) {
109 result[value] = $element.attr(value);
110 $element.removeAttr(value);
111 });
112 return result;
113 },
114 // http://docs.jquery.com/Plugins/Validation/rules
115 rules: function(command, argument) {
116 var element = this[0];
117
118 if (command) {
119 var settings = $.data(element.form, 'validator').settings;
120 var staticRules = settings.rules;
121 var existingRules = $.validator.staticRules(element);
122 switch(command) {
123 case "add":
124 $.extend(existingRules, $.validator.normalizeRule(argument));
125 staticRules[element.name] = existingRules;
126 if (argument.messages)
127 settings.messages[element.name] = $.extend( settings.messages[element.name], argument.messages );
128 break;
129 case "remove":
130 if (!argument) {
131 delete staticRules[element.name];
132 return existingRules;
133 }
134 var filtered = {};
135 $.each(argument.split(/\s/), function(index, method) {
136 filtered[method] = existingRules[method];
137 delete existingRules[method];
138 });
139 return filtered;
140 }
141 }
142
143 var data = $.validator.normalizeRules(
144 $.extend(
145 {},
146 $.validator.metadataRules(element),
147 $.validator.classRules(element),
148 // commenting out default validations, CRM-8334
149 // $.validator.attributeRules(element),
150 $.validator.staticRules(element)
151 ), element);
152
153 // make sure required is at front
154 if (data.required) {
155 var param = data.required;
156 delete data.required;
157 data = $.extend({required: param}, data);
158 }
159
160 return data;
161 }
162});
163
164// Custom selectors
165$.extend($.expr[":"], {
166 // http://docs.jquery.com/Plugins/Validation/blank
167 blank: function(a) {return !$.trim("" + a.value);},
168 // http://docs.jquery.com/Plugins/Validation/filled
169 filled: function(a) {return !!$.trim("" + a.value);},
170 // http://docs.jquery.com/Plugins/Validation/unchecked
171 unchecked: function(a) {return !a.checked;}
172});
173
174// constructor for validator
175$.validator = function( options, form ) {
176 this.settings = $.extend( true, {}, $.validator.defaults, options );
177 this.currentForm = form;
178 this.init();
179};
180
181$.validator.format = function(source, params) {
182 if ( arguments.length == 1 )
183 return function() {
184 var args = $.makeArray(arguments);
185 args.unshift(source);
186 return $.validator.format.apply( this, args );
187 };
188 if ( arguments.length > 2 && params.constructor != Array ) {
189 params = $.makeArray(arguments).slice(1);
190 }
191 if ( params.constructor != Array ) {
192 params = [ params ];
193 }
194 $.each(params, function(i, n) {
195 source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
196 });
197 return source;
198};
199
200$.extend($.validator, {
201
202 defaults: {
203 messages: {},
204 groups: {},
205 rules: {},
206 errorClass: "error",
207 validClass: "valid",
208 errorElement: "label",
209 focusInvalid: true,
210 errorContainer: $( [] ),
211 errorLabelContainer: $( [] ),
212 onsubmit: true,
213 ignore: [],
214 ignoreTitle: false,
215 onfocusin: function(element) {
216 this.lastActive = element;
217
218 // hide error label and remove error class on focus if enabled
219 if ( this.settings.focusCleanup && !this.blockFocusCleanup ) {
220 this.settings.unhighlight && this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass );
221 this.addWrapper(this.errorsFor(element)).hide();
222 }
223 },
224 onfocusout: function(element) {
225 if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
226 this.element(element);
227 }
228 },
229 onkeyup: function(element) {
230 if ( element.name in this.submitted || element == this.lastElement ) {
231 this.element(element);
232 }
233 },
234 onclick: function(element) {
235 // click on selects, radiobuttons and checkboxes
236 if ( element.name in this.submitted )
237 this.element(element);
238 // or option elements, check parent select in that case
239 else if (element.parentNode.name in this.submitted)
240 this.element(element.parentNode);
241 },
242 highlight: function( element, errorClass, validClass ) {
243 $(element).addClass(errorClass).removeClass(validClass);
244 },
245 unhighlight: function( element, errorClass, validClass ) {
246 $(element).removeClass(errorClass).addClass(validClass);
247 }
248 },
249
250 // http://docs.jquery.com/Plugins/Validation/Validator/setDefaults
251 setDefaults: function(settings) {
252 $.extend( $.validator.defaults, settings );
253 },
254
255 messages: {
256 required: "This field is required.",
257 remote: "Please fix this field.",
258 email: "Please enter a valid email address.",
259 url: "Please enter a valid URL.",
260 date: "Please enter a valid date.",
261 dateISO: "Please enter a valid date (ISO).",
262 number: "Please enter a valid number.",
263 digits: "Please enter only digits.",
264 creditcard: "Please enter a valid credit card number.",
265 equalTo: "Please enter the same value again.",
266 accept: "Please enter a value with a valid extension.",
267 maxlength: $.validator.format("Please enter no more than {0} characters."),
268 minlength: $.validator.format("Please enter at least {0} characters."),
269 rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
270 range: $.validator.format("Please enter a value between {0} and {1}."),
271 max: $.validator.format("Please enter a value less than or equal to {0}."),
272 min: $.validator.format("Please enter a value greater than or equal to {0}.")
273 },
274
275 autoCreateRanges: false,
276
277 prototype: {
278
279 init: function() {
280 this.labelContainer = $(this.settings.errorLabelContainer);
281 this.errorContext = this.labelContainer.length && this.labelContainer || $(this.currentForm);
282 this.containers = $(this.settings.errorContainer).add( this.settings.errorLabelContainer );
283 this.submitted = {};
284 this.valueCache = {};
285 this.pendingRequest = 0;
286 this.pending = {};
287 this.invalid = {};
288 this.reset();
289
290 var groups = (this.groups = {});
291 $.each(this.settings.groups, function(key, value) {
292 $.each(value.split(/\s/), function(index, name) {
293 groups[name] = key;
294 });
295 });
296 var rules = this.settings.rules;
297 $.each(rules, function(key, value) {
298 rules[key] = $.validator.normalizeRule(value);
299 });
300
301 function delegate(event) {
302 var validator = $.data(this[0].form, "validator"),
303 eventType = "on" + event.type.replace(/^validate/, "");
304 if (!validator)
305 return;
306 validator.settings[eventType] && validator.settings[eventType].call(validator, this[0] );
307 }
308 $(this.currentForm)
309 .validateDelegate(":text, :password, :file, select, textarea", "focusin focusout keyup", delegate)
310 .validateDelegate(":radio, :checkbox, select, option", "click", delegate);
311
312 if (this.settings.invalidHandler)
313 $(this.currentForm).bind("invalid-form.validate", this.settings.invalidHandler);
314 },
315
316 // http://docs.jquery.com/Plugins/Validation/Validator/form
317 form: function() {
318 this.checkForm();
319 $.extend(this.submitted, this.errorMap);
320 this.invalid = $.extend({}, this.errorMap);
321 if (!this.valid())
322 $(this.currentForm).triggerHandler("invalid-form", [this]);
323 this.showErrors();
324 return this.valid();
325 },
326
327 checkForm: function() {
328 this.prepareForm();
329 for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
330 this.check( elements[i] );
331 }
332 return this.valid();
333 },
334
335 // http://docs.jquery.com/Plugins/Validation/Validator/element
336 element: function( element ) {
337 element = this.clean( element );
338 this.lastElement = element;
339 this.prepareElement( element );
340 this.currentElements = $(element);
341 var result = this.check( element );
342 if ( result ) {
343 delete this.invalid[element.name];
344 } else {
345 this.invalid[element.name] = true;
346 }
347 if ( !this.numberOfInvalids() ) {
348 // Hide error containers on last error
349 this.toHide = this.toHide.add( this.containers );
350 }
351 this.showErrors();
352 return result;
353 },
354
355 // http://docs.jquery.com/Plugins/Validation/Validator/showErrors
356 showErrors: function(errors) {
357 if(errors) {
358 // add items to error list and map
359 $.extend( this.errorMap, errors );
360 this.errorList = [];
361 for ( var name in errors ) {
362 this.errorList.push({
363 message: errors[name],
364 element: this.findByName(name)[0]
365 });
366 }
367 // remove items from success list
368 this.successList = $.grep( this.successList, function(element) {
369 return !(element.name in errors);
370 });
371 }
372 this.settings.showErrors
373 ? this.settings.showErrors.call( this, this.errorMap, this.errorList )
374 : this.defaultShowErrors();
375 },
376
377 // http://docs.jquery.com/Plugins/Validation/Validator/resetForm
378 resetForm: function() {
379 if ( $.fn.resetForm )
380 $( this.currentForm ).resetForm();
381 this.submitted = {};
382 this.prepareForm();
383 this.hideErrors();
384 this.elements().removeClass( this.settings.errorClass );
385 },
386
387 numberOfInvalids: function() {
388 return this.objectLength(this.invalid);
389 },
390
391 objectLength: function( obj ) {
392 var count = 0;
393 for ( var i in obj )
394 count++;
395 return count;
396 },
397
398 hideErrors: function() {
399 this.addWrapper( this.toHide ).hide();
400 },
401
402 valid: function() {
403 return this.size() == 0;
404 },
405
406 size: function() {
407 return this.errorList.length;
408 },
409
410 focusInvalid: function() {
411 if( this.settings.focusInvalid ) {
412 try {
413 $(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
414 .filter(":visible")
415 .focus()
416 // manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
417 .trigger("focusin");
418 } catch(e) {
419 // ignore IE throwing errors when focusing hidden elements
420 }
421 }
422 },
423
424 findLastActive: function() {
425 var lastActive = this.lastActive;
426 return lastActive && $.grep(this.errorList, function(n) {
427 return n.element.name == lastActive.name;
428 }).length == 1 && lastActive;
429 },
430
431 elements: function() {
432 var validator = this,
433 rulesCache = {};
434
435 // select all valid inputs inside the form (no submit or reset buttons)
436 // workaround $Query([]).add until http://dev.jquery.com/ticket/2114 is solved
437 return $([]).add(this.currentForm.elements)
438 .filter(":input")
439 .not(":submit, :reset, :image, [disabled]")
440 .not( this.settings.ignore )
441 .filter(function() {
442 !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);
443
444 // select only the first element for each name, and only those with rules specified
445 if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
446 return false;
447
448 rulesCache[this.name] = true;
449 return true;
450 });
451 },
452
453 clean: function( selector ) {
454 return $( selector )[0];
455 },
456
457 errors: function() {
458 return $( this.settings.errorElement + "." + this.settings.errorClass, this.errorContext );
459 },
460
461 reset: function() {
462 this.successList = [];
463 this.errorList = [];
464 this.errorMap = {};
465 this.toShow = $([]);
466 this.toHide = $([]);
467 this.currentElements = $([]);
468 },
469
470 prepareForm: function() {
471 this.reset();
472 this.toHide = this.errors().add( this.containers );
473 },
474
475 prepareElement: function( element ) {
476 this.reset();
477 this.toHide = this.errorsFor(element);
478 },
479
480 check: function( element ) {
481 element = this.clean( element );
482
483 // if radio/checkbox, validate first element in group instead
484 if (this.checkable(element)) {
485 element = this.findByName( element.name ).not(this.settings.ignore)[0];
486 }
487
488 var rules = $(element).rules();
489 var dependencyMismatch = false;
490 for (var method in rules ) {
491 var rule = { method: method, parameters: rules[method] };
492 try {
493 var result = $.validator.methods[method].call( this, element.value.replace(/\r/g, ""), element, rule.parameters );
494
495 // if a method indicates that the field is optional and therefore valid,
496 // don't mark it as valid when there are no other rules
497 if ( result == "dependency-mismatch" ) {
498 dependencyMismatch = true;
499 continue;
500 }
501 dependencyMismatch = false;
502
503 if ( result == "pending" ) {
504 this.toHide = this.toHide.not( this.errorsFor(element) );
505 return;
506 }
507
508 if( !result ) {
509 this.formatAndAdd( element, rule );
510 return false;
511 }
512 } catch(e) {
513 this.settings.debug && window.console && console.log("exception occured when checking element " + element.id
514 + ", check the '" + rule.method + "' method", e);
515 throw e;
516 }
517 }
518 if (dependencyMismatch)
519 return;
520 if ( this.objectLength(rules) )
521 this.successList.push(element);
522 return true;
523 },
524
525 // return the custom message for the given element and validation method
526 // specified in the element's "messages" metadata
527 customMetaMessage: function(element, method) {
528 if (!$.metadata)
529 return;
530
531 var meta = this.settings.meta
532 ? $(element).metadata()[this.settings.meta]
533 : $(element).metadata();
534
535 return meta && meta.messages && meta.messages[method];
536 },
537
538 // return the custom message for the given element name and validation method
539 customMessage: function( name, method ) {
540 var m = this.settings.messages[name];
541 return m && (m.constructor == String
542 ? m
543 : m[method]);
544 },
545
546 // return the first defined argument, allowing empty strings
547 findDefined: function() {
548 for(var i = 0; i < arguments.length; i++) {
549 if (arguments[i] !== undefined)
550 return arguments[i];
551 }
552 return undefined;
553 },
554
555 defaultMessage: function( element, method) {
556 return this.findDefined(
557 this.customMessage( element.name, method ),
558 this.customMetaMessage( element, method ),
559 // title is never undefined, so handle empty string as undefined
560 !this.settings.ignoreTitle && element.title || undefined,
561 $.validator.messages[method],
562 "<strong>Warning: No message defined for " + element.name + "</strong>"
563 );
564 },
565
566 formatAndAdd: function( element, rule ) {
567 var message = this.defaultMessage( element, rule.method ),
568 theregex = /\$?\{(\d+)\}/g;
569 if ( typeof message == "function" ) {
570 message = message.call(this, rule.parameters, element);
571 } else if (theregex.test(message)) {
572 message = jQuery.format(message.replace(theregex, '{$1}'), rule.parameters);
573 }
574 this.errorList.push({
575 message: message,
576 element: element
577 });
578
579 this.errorMap[element.name] = message;
580 this.submitted[element.name] = message;
581 },
582
583 addWrapper: function(toToggle) {
584 if ( this.settings.wrapper )
585 toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) );
586 return toToggle;
587 },
588
589 defaultShowErrors: function() {
590 for ( var i = 0; this.errorList[i]; i++ ) {
591 var error = this.errorList[i];
592 this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
593 this.showLabel( error.element, error.message );
594 }
595 if( this.errorList.length ) {
596 this.toShow = this.toShow.add( this.containers );
597 }
598 if (this.settings.success) {
599 for ( var i = 0; this.successList[i]; i++ ) {
600 this.showLabel( this.successList[i] );
601 }
602 }
603 if (this.settings.unhighlight) {
604 for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
605 this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
606 }
607 }
608 this.toHide = this.toHide.not( this.toShow );
609 this.hideErrors();
610 this.addWrapper( this.toShow ).show();
611 },
612
613 validElements: function() {
614 return this.currentElements.not(this.invalidElements());
615 },
616
617 invalidElements: function() {
618 return $(this.errorList).map(function() {
619 return this.element;
620 });
621 },
622
623 showLabel: function(element, message) {
624 var label = this.errorsFor( element );
625 if ( label.length ) {
626 // refresh error/success class
627 label.removeClass().addClass( this.settings.errorClass );
628
629 // check if we have a generated label, replace the message then
630 label.attr("generated") && label.html(message);
631 } else {
632 // create label
633 label = $("<" + this.settings.errorElement + "/>")
634 .attr({"for": this.idOrName(element), generated: true})
635 .addClass(this.settings.errorClass)
636 .html(message || "");
637 if ( this.settings.wrapper ) {
638 // make sure the element is visible, even in IE
639 // actually showing the wrapped element is handled elsewhere
640 label = label.hide().show().wrap("<" + this.settings.wrapper + "/>").parent();
641 }
642 if ( !this.labelContainer.append(label).length )
643 this.settings.errorPlacement
644 ? this.settings.errorPlacement(label, $(element) )
645 : label.insertAfter(element);
646 }
647 if ( !message && this.settings.success ) {
648 label.text("");
649 typeof this.settings.success == "string"
650 ? label.addClass( this.settings.success )
651 : this.settings.success( label );
652 }
653 this.toShow = this.toShow.add(label);
654 },
655
656 errorsFor: function(element) {
657 var name = this.idOrName(element);
658 return this.errors().filter(function() {
659 return $(this).attr('for') == name;
660 });
661 },
662
663 idOrName: function(element) {
664 return this.groups[element.name] || (this.checkable(element) ? element.name : element.id || element.name);
665 },
666
667 checkable: function( element ) {
668 return /radio|checkbox/i.test(element.type);
669 },
670
671 findByName: function( name ) {
672 // select by name and filter by form for performance over form.find("[name=...]")
673 var form = this.currentForm;
674 return $(document.getElementsByName(name)).map(function(index, element) {
675 return element.form == form && element.name == name && element || null;
676 });
677 },
678
679 getLength: function(value, element) {
680 switch( element.nodeName.toLowerCase() ) {
681 case 'select':
682 return $("option:selected", element).length;
683 case 'input':
684 if( this.checkable( element) )
685 return this.findByName(element.name).filter(':checked').length;
686 }
687 return value.length;
688 },
689
690 depend: function(param, element) {
691 return this.dependTypes[typeof param]
692 ? this.dependTypes[typeof param](param, element)
693 : true;
694 },
695
696 dependTypes: {
697 "boolean": function(param, element) {
698 return param;
699 },
700 "string": function(param, element) {
701 return !!$(param, element.form).length;
702 },
703 "function": function(param, element) {
704 return param(element);
705 }
706 },
707
708 optional: function(element) {
709 return !$.validator.methods.required.call(this, $.trim(element.value), element) && "dependency-mismatch";
710 },
711
712 startRequest: function(element) {
713 if (!this.pending[element.name]) {
714 this.pendingRequest++;
715 this.pending[element.name] = true;
716 }
717 },
718
719 stopRequest: function(element, valid) {
720 this.pendingRequest--;
721 // sometimes synchronization fails, make sure pendingRequest is never < 0
722 if (this.pendingRequest < 0)
723 this.pendingRequest = 0;
724 delete this.pending[element.name];
725 if ( valid && this.pendingRequest == 0 && this.formSubmitted && this.form() ) {
726 $(this.currentForm).submit();
727 this.formSubmitted = false;
728 } else if (!valid && this.pendingRequest == 0 && this.formSubmitted) {
729 $(this.currentForm).triggerHandler("invalid-form", [this]);
730 this.formSubmitted = false;
731 }
732 },
733
734 previousValue: function(element) {
735 return $.data(element, "previousValue") || $.data(element, "previousValue", {
736 old: null,
737 valid: true,
738 message: this.defaultMessage( element, "remote" )
739 });
740 }
741
742 },
743
744 classRuleSettings: {
745 /*
746 // commenting all default validation rules
747 required: {required: true},
748 email: {email: true},
749 url: {url: true},
750 date: {date: true},
751 dateISO: {dateISO: true},
752 dateDE: {dateDE: true},
753 number: {number: true},
754 numberDE: {numberDE: true},
755 digits: {digits: true},
756 creditcard: {creditcard: true}
757 */
758 },
759
760 addClassRules: function(className, rules) {
761 className.constructor == String ?
762 this.classRuleSettings[className] = rules :
763 $.extend(this.classRuleSettings, className);
764 },
765
766 classRules: function(element) {
767 var rules = {};
768 var classes = $(element).attr('class');
769 classes && $.each(classes.split(' '), function() {
770 if (this in $.validator.classRuleSettings) {
771 $.extend(rules, $.validator.classRuleSettings[this]);
772 }
773 });
774 return rules;
775 },
776
777 attributeRules: function(element) {
778 var rules = {};
779 var $element = $(element);
780
781 for (var method in $.validator.methods) {
782 var value = $element.attr(method);
783 if (value) {
784 rules[method] = value;
785 }
786 }
787
788 // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
789 if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
790 delete rules.maxlength;
791 }
792
793 return rules;
794 },
795
796 metadataRules: function(element) {
797 if (!$.metadata) return {};
798
799 var meta = $.data(element.form, 'validator').settings.meta;
800 return meta ?
801 $(element).metadata()[meta] :
802 $(element).metadata();
803 },
804
805 staticRules: function(element) {
806 var rules = {};
807 var validator = $.data(element.form, 'validator');
808 if (validator.settings.rules) {
809 rules = $.validator.normalizeRule(validator.settings.rules[element.name]) || {};
810 }
811 return rules;
812 },
813
814 normalizeRules: function(rules, element) {
815 // handle dependency check
816 $.each(rules, function(prop, val) {
817 // ignore rule when param is explicitly false, eg. required:false
818 if (val === false) {
819 delete rules[prop];
820 return;
821 }
822 if (val.param || val.depends) {
823 var keepRule = true;
824 switch (typeof val.depends) {
825 case "string":
826 keepRule = !!$(val.depends, element.form).length;
827 break;
828 case "function":
829 keepRule = val.depends.call(element, element);
830 break;
831 }
832 if (keepRule) {
833 rules[prop] = val.param !== undefined ? val.param : true;
834 } else {
835 delete rules[prop];
836 }
837 }
838 });
839
840 // evaluate parameters
841 $.each(rules, function(rule, parameter) {
842 rules[rule] = $.isFunction(parameter) ? parameter(element) : parameter;
843 });
844
845 // clean number parameters
846 $.each(['minlength', 'maxlength', 'min', 'max'], function() {
847 if (rules[this]) {
848 rules[this] = Number(rules[this]);
849 }
850 });
851 $.each(['rangelength', 'range'], function() {
852 if (rules[this]) {
853 rules[this] = [Number(rules[this][0]), Number(rules[this][1])];
854 }
855 });
856
857 if ($.validator.autoCreateRanges) {
858 // auto-create ranges
859 if (rules.min && rules.max) {
860 rules.range = [rules.min, rules.max];
861 delete rules.min;
862 delete rules.max;
863 }
864 if (rules.minlength && rules.maxlength) {
865 rules.rangelength = [rules.minlength, rules.maxlength];
866 delete rules.minlength;
867 delete rules.maxlength;
868 }
869 }
870
871 // To support custom messages in metadata ignore rule methods titled "messages"
872 if (rules.messages) {
873 delete rules.messages;
874 }
875
876 return rules;
877 },
878
879 // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true}
880 normalizeRule: function(data) {
881 if( typeof data == "string" ) {
882 var transformed = {};
883 $.each(data.split(/\s/), function() {
884 transformed[this] = true;
885 });
886 data = transformed;
887 }
888 return data;
889 },
890
891 // http://docs.jquery.com/Plugins/Validation/Validator/addMethod
892 addMethod: function(name, method, message) {
893 $.validator.methods[name] = method;
894 $.validator.messages[name] = message != undefined ? message : $.validator.messages[name];
895 if (method.length < 3) {
896 $.validator.addClassRules(name, $.validator.normalizeRule(name));
897 }
898 },
899
900 methods: {
901
902 // http://docs.jquery.com/Plugins/Validation/Methods/required
903 required: function(value, element, param) {
904 // check if dependency is met
905 if ( !this.depend(param, element) )
906 return "dependency-mismatch";
907 switch( element.nodeName.toLowerCase() ) {
908 case 'select':
909 // could be an array for select-multiple or a string, both are fine this way
910 var val = $(element).val();
911 return val && val.length > 0;
912 case 'input':
913 if ( this.checkable(element) )
914 return this.getLength(value, element) > 0;
915 default:
916 return $.trim(value).length > 0;
917 }
918 },
919
920 // http://docs.jquery.com/Plugins/Validation/Methods/remote
921 remote: function(value, element, param) {
922 if ( this.optional(element) )
923 return "dependency-mismatch";
924
925 var previous = this.previousValue(element);
926 if (!this.settings.messages[element.name] )
927 this.settings.messages[element.name] = {};
928 previous.originalMessage = this.settings.messages[element.name].remote;
929 this.settings.messages[element.name].remote = previous.message;
930
931 param = typeof param == "string" && {url:param} || param;
932
933 if ( this.pending[element.name] ) {
934 return "pending";
935 }
936 if ( previous.old === value ) {
937 return previous.valid;
938 }
939
940 previous.old = value;
941 var validator = this;
942 this.startRequest(element);
943 var data = {};
944 data[element.name] = value;
945 $.ajax($.extend(true, {
946 url: param,
947 mode: "abort",
948 port: "validate" + element.name,
949 dataType: "json",
950 data: data,
951 success: function(response) {
952 validator.settings.messages[element.name].remote = previous.originalMessage;
953 var valid = response === true;
954 if ( valid ) {
955 var submitted = validator.formSubmitted;
956 validator.prepareElement(element);
957 validator.formSubmitted = submitted;
958 validator.successList.push(element);
959 validator.showErrors();
960 } else {
961 var errors = {};
962 var message = response || validator.defaultMessage( element, "remote" );
963 errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
964 validator.showErrors(errors);
965 }
966 previous.valid = valid;
967 validator.stopRequest(element, valid);
968 }
969 }, param));
970 return "pending";
971 },
972
973 // http://docs.jquery.com/Plugins/Validation/Methods/minlength
974 minlength: function(value, element, param) {
975 return this.optional(element) || this.getLength($.trim(value), element) >= param;
976 },
977
978 // http://docs.jquery.com/Plugins/Validation/Methods/maxlength
979 maxlength: function(value, element, param) {
980 return this.optional(element) || this.getLength($.trim(value), element) <= param;
981 },
982
983 // http://docs.jquery.com/Plugins/Validation/Methods/rangelength
984 rangelength: function(value, element, param) {
985 var length = this.getLength($.trim(value), element);
986 return this.optional(element) || ( length >= param[0] && length <= param[1] );
987 },
988
989 // http://docs.jquery.com/Plugins/Validation/Methods/min
990 min: function( value, element, param ) {
991 return this.optional(element) || value >= param;
992 },
993
994 // http://docs.jquery.com/Plugins/Validation/Methods/max
995 max: function( value, element, param ) {
996 return this.optional(element) || value <= param;
997 },
998
999 // http://docs.jquery.com/Plugins/Validation/Methods/range
1000 range: function( value, element, param ) {
1001 return this.optional(element) || ( value >= param[0] && value <= param[1] );
1002 },
1003
1004 // http://docs.jquery.com/Plugins/Validation/Methods/email
1005 email: function(value, element) {
1006 // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
1007 return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\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])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
1008 },
1009
1010 // http://docs.jquery.com/Plugins/Validation/Methods/url
1011 url: function(value, element) {
1012 // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
1013 return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\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])([a-z]|\d|-|\.|_|~|[\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])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
1014 },
1015
1016 // http://docs.jquery.com/Plugins/Validation/Methods/date
1017 date: function(value, element) {
1018 return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
1019 },
1020
1021 // http://docs.jquery.com/Plugins/Validation/Methods/dateISO
1022 dateISO: function(value, element) {
1023 return this.optional(element) || /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);
1024 },
1025
1026 // http://docs.jquery.com/Plugins/Validation/Methods/number
1027 number: function(value, element) {
1028 return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
1029 },
1030
1031 // http://docs.jquery.com/Plugins/Validation/Methods/digits
1032 digits: function(value, element) {
1033 return this.optional(element) || /^\d+$/.test(value);
1034 },
1035
1036 // http://docs.jquery.com/Plugins/Validation/Methods/creditcard
1037 // based on http://en.wikipedia.org/wiki/Luhn
1038 creditcard: function(value, element) {
1039 if ( this.optional(element) )
1040 return "dependency-mismatch";
1041 // accept only digits and dashes
1042 if (/[^0-9-]+/.test(value))
1043 return false;
1044 var nCheck = 0,
1045 nDigit = 0,
1046 bEven = false;
1047
1048 value = value.replace(/\D/g, "");
1049
1050 for (var n = value.length - 1; n >= 0; n--) {
1051 var cDigit = value.charAt(n);
1052 var nDigit = parseInt(cDigit, 10);
1053 if (bEven) {
1054 if ((nDigit *= 2) > 9)
1055 nDigit -= 9;
1056 }
1057 nCheck += nDigit;
1058 bEven = !bEven;
1059 }
1060
1061 return (nCheck % 10) == 0;
1062 },
1063
1064 // http://docs.jquery.com/Plugins/Validation/Methods/accept
1065 accept: function(value, element, param) {
1066 param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
1067 return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
1068 },
1069
1070 // http://docs.jquery.com/Plugins/Validation/Methods/equalTo
1071 equalTo: function(value, element, param) {
1072 // bind to the blur event of the target in order to revalidate whenever the target field is updated
1073 // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
1074 var target = $(param).unbind(".validate-equalTo").bind("blur.validate-equalTo", function() {
1075 $(element).valid();
1076 });
1077 return value == target.val();
1078 }
1079
1080 }
1081
1082});
1083
1084// deprecated, use $.validator.format instead
1085$.format = $.validator.format;
1086
1087})(jQuery);
1088
1089// ajax mode: abort
1090// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
1091// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
1092;(function($) {
1093 var pendingRequests = {};
1094 // Use a prefilter if available (1.5+)
1095 if ( $.ajaxPrefilter ) {
1096 $.ajaxPrefilter(function(settings, _, xhr) {
1097 var port = settings.port;
1098 if (settings.mode == "abort") {
1099 if ( pendingRequests[port] ) {
1100 pendingRequests[port].abort();
1101 }
1102 pendingRequests[port] = xhr;
1103 }
1104 });
1105 } else {
1106 // Proxy ajax
1107 var ajax = $.ajax;
1108 $.ajax = function(settings) {
1109 var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
1110 port = ( "port" in settings ? settings : $.ajaxSettings ).port;
1111 if (mode == "abort") {
1112 if ( pendingRequests[port] ) {
1113 pendingRequests[port].abort();
1114 }
1115 return (pendingRequests[port] = ajax.apply(this, arguments));
1116 }
1117 return ajax.apply(this, arguments);
1118 };
1119 }
1120})(jQuery);
1121
1122// provides cross-browser focusin and focusout events
1123// IE has native support, in other browsers, use event caputuring (neither bubbles)
1124
1125// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
1126// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
1127;(function($) {
1128 // only implement if not provided by jQuery core (since 1.4)
1129 // TODO verify if jQuery 1.4's implementation is compatible with older jQuery special-event APIs
1130 if (!jQuery.event.special.focusin && !jQuery.event.special.focusout && document.addEventListener) {
1131 $.each({
1132 focus: 'focusin',
1133 blur: 'focusout'
1134 }, function( original, fix ){
1135 $.event.special[fix] = {
1136 setup:function() {
1137 this.addEventListener( original, handler, true );
1138 },
1139 teardown:function() {
1140 this.removeEventListener( original, handler, true );
1141 },
1142 handler: function(e) {
1143 arguments[0] = $.event.fix(e);
1144 arguments[0].type = fix;
1145 return $.event.handle.apply(this, arguments);
1146 }
1147 };
1148 function handler(e) {
1149 e = $.event.fix(e);
1150 e.type = fix;
1151 return $.event.handle.call(this, e);
1152 }
1153 });
1154 };
1155 $.extend($.fn, {
1156 validateDelegate: function(delegate, type, handler) {
1157 return this.bind(type, function(event) {
1158 var target = $(event.target);
1159 if (target.is(delegate)) {
1160 return handler.apply(target, arguments);
1161 }
1162 });
1163 }
1164 });
1165})(jQuery);