Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Services.Optimization.Web/Scripts/jquery.validate.js @ 12247

Last change on this file since 12247 was 9582, checked in by fschoepp, 11 years ago

#1888:

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