lavkach3

Форк
0
1198 строк · 45.6 Кб
1
/* jqBootstrapValidation
2
 * A plugin for automating validation on Twitter Bootstrap formatted forms.
3
 *
4
 * v1.3.6
5
 *
6
 * License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
7
 *
8
 * http://ReactiveRaven.github.com/jqBootstrapValidation/
9
 */
10
(function ($) {
11
    var createdElements = [];
12
    var defaults = {
13
      options: {
14
        prependExistingHelpBlock: false,
15
        sniffHtml: true, // sniff for 'required', 'maxlength', etc
16
        preventSubmit: true, // stop the form submit event from firing if validation fails
17
        submitError: false, // function called if there is an error when trying to submit
18
        submitSuccess: false, // function called just before a successful submit event is sent to the server
19
        semanticallyStrict: false, // set to true to tidy up generated HTML output
20
        bindEvents: [],
21
        autoAdd: {
22
          helpBlocks: true,
23
        },
24
        filter: function () {
25
          // return $(this).is(":visible"); // only validate elements you can see
26
          return true; // validate everything
27
        },
28
      },
29
      methods: {
30
        init: function (options) {
31
          var settings = $.extend(true, {}, defaults);
32
          settings.options = $.extend(true, settings.options, options);
33
          var $siblingElements = this;
34
          var uniqueForms = $.unique(
35
            $siblingElements
36
              .map(function () {
37
                return $(this).parents("form")[0];
38
              })
39
              .toArray()
40
          );
41
          $(uniqueForms).bind("submit.validationSubmit", function (e) {
42
            var $form = $(this);
43
            var warningsFound = 0;
44
            var $allInputs = $form
45
              .find("input,textarea,select")
46
              .not("[type=submit],[type=image]")
47
              .filter(settings.options.filter);
48
            var $allControlGroups = $form.find(".form-group");
49
            var $inputsWithValidators = $allInputs.filter(function () {
50
              return $(this).triggerHandler("getValidatorCount.validation") > 0;
51
            });
52
            $inputsWithValidators.trigger("submit.validation");
53
            $allInputs.trigger("validationLostFocus.validation");
54
            $allControlGroups.each(function (i, el) {
55
              var $controlGroup = $(el);
56
              if (
57
                $controlGroup.hasClass("issue") ||
58
                $controlGroup.hasClass("error")
59
              ) {
60
                $controlGroup.removeClass("issue").addClass("error");
61
                warningsFound++;
62
              }
63
            });
64
            if (warningsFound) {
65
              if (settings.options.preventSubmit) {
66
                e.preventDefault();
67
                e.stopImmediatePropagation();
68
              }
69
              $form.addClass("error");
70
              if ($.isFunction(settings.options.submitError)) {
71
                settings.options.submitError(
72
                  $form,
73
                  e,
74
                  $inputsWithValidators.jqBootstrapValidation(
75
                    "collectErrors",
76
                    true
77
                  )
78
                );
79
              }
80
            } else {
81
              $form.removeClass("error");
82
              if ($.isFunction(settings.options.submitSuccess)) {
83
                settings.options.submitSuccess($form, e);
84
              }
85
            }
86
          });
87
          return this.each(function () {
88
            var $this = $(this),
89
              $controlGroup = $this.parents(".form-group").first(),
90
              $helpBlock = $controlGroup.find(".help-block").first(),
91
              $form = $this.parents("form").first(),
92
              validatorNames = [];
93
            if (
94
              !$helpBlock.length &&
95
              settings.options.autoAdd &&
96
              settings.options.autoAdd.helpBlocks
97
            ) {
98
              $helpBlock = $('<div class="help-block" />');
99
              $controlGroup.find(".controls").append($helpBlock);
100
              createdElements.push($helpBlock[0]);
101
            }
102
            if (settings.options.sniffHtml) {
103
              var message;
104
              if ($this.data("validationPatternPattern")) {
105
                $this.attr("pattern", $this.data("validationPatternPattern"));
106
              }
107
              if ($this.attr("pattern") !== undefined) {
108
                message =
109
                  "Not in the expected format<!-- data-validation-pattern-message to override -->";
110
                if ($this.data("validationPatternMessage")) {
111
                  message = $this.data("validationPatternMessage");
112
                }
113
                $this.data("validationPatternMessage", message);
114
                $this.data("validationPatternRegex", $this.attr("pattern"));
115
              }
116
              if (
117
                $this.attr("max") !== undefined ||
118
                $this.attr("aria-valuemax") !== undefined
119
              ) {
120
                var max =
121
                  $this.attr("max") !== undefined
122
                    ? $this.attr("max")
123
                    : $this.attr("aria-valuemax");
124
                message =
125
                  "Too high: Maximum of '" +
126
                  max +
127
                  "'<!-- data-validation-max-message to override -->";
128
                if ($this.data("validationMaxMessage")) {
129
                  message = $this.data("validationMaxMessage");
130
                }
131
                $this.data("validationMaxMessage", message);
132
                $this.data("validationMaxMax", max);
133
              }
134
              if (
135
                $this.attr("min") !== undefined ||
136
                $this.attr("aria-valuemin") !== undefined
137
              ) {
138
                var min =
139
                  $this.attr("min") !== undefined
140
                    ? $this.attr("min")
141
                    : $this.attr("aria-valuemin");
142
                message =
143
                  "Too low: Minimum of '" +
144
                  min +
145
                  "'<!-- data-validation-min-message to override -->";
146
                if ($this.data("validationMinMessage")) {
147
                  message = $this.data("validationMinMessage");
148
                }
149
                $this.data("validationMinMessage", message);
150
                $this.data("validationMinMin", min);
151
              }
152
              if ($this.attr("maxlength") !== undefined) {
153
                message =
154
                  "Too long: Maximum of '" +
155
                  $this.attr("maxlength") +
156
                  "' characters<!-- data-validation-maxlength-message to override -->";
157
                if ($this.data("validationMaxlengthMessage")) {
158
                  message = $this.data("validationMaxlengthMessage");
159
                }
160
                $this.data("validationMaxlengthMessage", message);
161
                $this.data(
162
                  "validationMaxlengthMaxlength",
163
                  $this.attr("maxlength")
164
                );
165
              }
166
              if ($this.attr("minlength") !== undefined) {
167
                message =
168
                  "Too short: Minimum of '" +
169
                  $this.attr("minlength") +
170
                  "' characters<!-- data-validation-minlength-message to override -->";
171
                if ($this.data("validationMinlengthMessage")) {
172
                  message = $this.data("validationMinlengthMessage");
173
                }
174
                $this.data("validationMinlengthMessage", message);
175
                $this.data(
176
                  "validationMinlengthMinlength",
177
                  $this.attr("minlength")
178
                );
179
              }
180
              if (
181
                $this.attr("required") !== undefined ||
182
                $this.attr("aria-required") !== undefined
183
              ) {
184
                message = settings.builtInValidators.required.message;
185
                if ($this.data("validationRequiredMessage")) {
186
                  message = $this.data("validationRequiredMessage");
187
                }
188
                $this.data("validationRequiredMessage", message);
189
              }
190
              if (
191
                $this.attr("type") !== undefined &&
192
                $this.attr("type").toLowerCase() === "number"
193
              ) {
194
                message = settings.validatorTypes.number.message;
195
                if ($this.data("validationNumberMessage")) {
196
                  message = $this.data("validationNumberMessage");
197
                }
198
                $this.data("validationNumberMessage", message);
199
                var step = settings.validatorTypes.number.step;
200
                if ($this.data("validationNumberStep")) {
201
                  step = $this.data("validationNumberStep");
202
                }
203
                $this.data("validationNumberStep", step);
204
                var decimal = settings.validatorTypes.number.decimal;
205
                if ($this.data("validationNumberDecimal")) {
206
                  decimal = $this.data("validationNumberDecimal");
207
                }
208
                $this.data("validationNumberDecimal", decimal);
209
              }
210
              if (
211
                $this.attr("type") !== undefined &&
212
                $this.attr("type").toLowerCase() === "email"
213
              ) {
214
                message =
215
                  "Not a valid email address<!-- data-validation-email-message to override -->";
216
                if ($this.data("validationEmailMessage")) {
217
                  message = $this.data("validationEmailMessage");
218
                }
219
                $this.data("validationEmailMessage", message);
220
              }
221
              if ($this.attr("minchecked") !== undefined) {
222
                message =
223
                  "Not enough options checked; Minimum of '" +
224
                  $this.attr("minchecked") +
225
                  "' required<!-- data-validation-minchecked-message to override -->";
226
                if ($this.data("validationMincheckedMessage")) {
227
                  message = $this.data("validationMincheckedMessage");
228
                }
229
                $this.data("validationMincheckedMessage", message);
230
                $this.data(
231
                  "validationMincheckedMinchecked",
232
                  $this.attr("minchecked")
233
                );
234
              }
235
              if ($this.attr("maxchecked") !== undefined) {
236
                message =
237
                  "Too many options checked; Maximum of '" +
238
                  $this.attr("maxchecked") +
239
                  "' required<!-- data-validation-maxchecked-message to override -->";
240
                if ($this.data("validationMaxcheckedMessage")) {
241
                  message = $this.data("validationMaxcheckedMessage");
242
                }
243
                $this.data("validationMaxcheckedMessage", message);
244
                $this.data(
245
                  "validationMaxcheckedMaxchecked",
246
                  $this.attr("maxchecked")
247
                );
248
              }
249
            }
250
            if ($this.data("validation") !== undefined) {
251
              validatorNames = $this.data("validation").split(",");
252
            }
253
            $.each($this.data(), function (i, el) {
254
              var parts = i.replace(/([A-Z])/g, ",$1").split(",");
255
              if (parts[0] === "validation" && parts[1]) {
256
                validatorNames.push(parts[1]);
257
              }
258
            });
259
            var validatorNamesToInspect = validatorNames;
260
            var newValidatorNamesToInspect = [];
261
            var uppercaseEachValidatorName = function (i, el) {
262
              validatorNames[i] = formatValidatorName(el);
263
            };
264
            var inspectValidators = function (i, el) {
265
              if ($this.data("validation" + el + "Shortcut") !== undefined) {
266
                $.each(
267
                  $this.data("validation" + el + "Shortcut").split(","),
268
                  function (i2, el2) {
269
                    newValidatorNamesToInspect.push(el2);
270
                  }
271
                );
272
              } else if (settings.builtInValidators[el.toLowerCase()]) {
273
                var validator = settings.builtInValidators[el.toLowerCase()];
274
                if (validator.type.toLowerCase() === "shortcut") {
275
                  $.each(validator.shortcut.split(","), function (i, el) {
276
                    el = formatValidatorName(el);
277
                    newValidatorNamesToInspect.push(el);
278
                    validatorNames.push(el);
279
                  });
280
                }
281
              }
282
            };
283
            do {
284
              $.each(validatorNames, uppercaseEachValidatorName);
285
              validatorNames = $.unique(validatorNames);
286
              newValidatorNamesToInspect = [];
287
              $.each(validatorNamesToInspect, inspectValidators);
288
              validatorNamesToInspect = newValidatorNamesToInspect;
289
            } while (validatorNamesToInspect.length > 0);
290
            var validators = {};
291
            $.each(validatorNames, function (i, el) {
292
              var message = $this.data("validation" + el + "Message");
293
              var hasOverrideMessage = !!message;
294
              var foundValidator = false;
295
              if (!message) {
296
                message =
297
                  "'" +
298
                  el +
299
                  "' validation failed <!-- Add attribute 'data-validation-" +
300
                  el.toLowerCase() +
301
                  "-message' to input to change this message -->";
302
              }
303
              $.each(
304
                settings.validatorTypes,
305
                function (validatorType, validatorTemplate) {
306
                  if (validators[validatorType] === undefined) {
307
                    validators[validatorType] = [];
308
                  }
309
                  if (
310
                    !foundValidator &&
311
                    $this.data(
312
                      "validation" +
313
                        el +
314
                        formatValidatorName(validatorTemplate.name)
315
                    ) !== undefined
316
                  ) {
317
                    var initted = validatorTemplate.init($this, el);
318
                    if (hasOverrideMessage) {
319
                      initted.message = message;
320
                    }
321
                    validators[validatorType].push(
322
                      $.extend(
323
                        true,
324
                        {
325
                          name: formatValidatorName(validatorTemplate.name),
326
                          message: message,
327
                        },
328
                        initted
329
                      )
330
                    );
331
                    foundValidator = true;
332
                  }
333
                }
334
              );
335
              if (
336
                !foundValidator &&
337
                settings.builtInValidators[el.toLowerCase()]
338
              ) {
339
                var validator = $.extend(
340
                  true,
341
                  {},
342
                  settings.builtInValidators[el.toLowerCase()]
343
                );
344
                if (hasOverrideMessage) {
345
                  validator.message = message;
346
                }
347
                var validatorType = validator.type.toLowerCase();
348
                if (validatorType === "shortcut") {
349
                  foundValidator = true;
350
                } else {
351
                  $.each(
352
                    settings.validatorTypes,
353
                    function (validatorTemplateType, validatorTemplate) {
354
                      if (validators[validatorTemplateType] === undefined) {
355
                        validators[validatorTemplateType] = [];
356
                      }
357
                      if (
358
                        !foundValidator &&
359
                        validatorType === validatorTemplateType.toLowerCase()
360
                      ) {
361
                        $this.data(
362
                          "validation" +
363
                            el +
364
                            formatValidatorName(validatorTemplate.name),
365
                          validator[validatorTemplate.name.toLowerCase()]
366
                        );
367
                        validators[validatorType].push(
368
                          $.extend(validator, validatorTemplate.init($this, el))
369
                        );
370
                        foundValidator = true;
371
                      }
372
                    }
373
                  );
374
                }
375
              }
376
              if (!foundValidator) {
377
                $.error("Cannot find validation info for '" + el + "'");
378
              }
379
            });
380
            $helpBlock.data(
381
              "original-contents",
382
              $helpBlock.data("original-contents")
383
                ? $helpBlock.data("original-contents")
384
                : $helpBlock.html()
385
            );
386
            $helpBlock.data(
387
              "original-role",
388
              $helpBlock.data("original-role")
389
                ? $helpBlock.data("original-role")
390
                : $helpBlock.attr("role")
391
            );
392
            $controlGroup.data(
393
              "original-classes",
394
              $controlGroup.data("original-clases")
395
                ? $controlGroup.data("original-classes")
396
                : $controlGroup.attr("class")
397
            );
398
            $this.data(
399
              "original-aria-invalid",
400
              $this.data("original-aria-invalid")
401
                ? $this.data("original-aria-invalid")
402
                : $this.attr("aria-invalid")
403
            );
404
            $this.bind("validation.validation", function (event, params) {
405
              var value = getValue($this);
406
              var errorsFound = [];
407
              $.each(validators, function (validatorType, validatorTypeArray) {
408
                if (
409
                  value ||
410
                  value.length ||
411
                  (params && params.includeEmpty) ||
412
                  !!settings.validatorTypes[validatorType].includeEmpty ||
413
                  (!!settings.validatorTypes[validatorType].blockSubmit &&
414
                    params &&
415
                    !!params.submitting)
416
                ) {
417
                  $.each(validatorTypeArray, function (i, validator) {
418
                    if (
419
                      settings.validatorTypes[validatorType].validate(
420
                        $this,
421
                        value,
422
                        validator
423
                      )
424
                    ) {
425
                      errorsFound.push(validator.message);
426
                    }
427
                  });
428
                }
429
              });
430
              return errorsFound;
431
            });
432
            $this.bind("getValidators.validation", function () {
433
              return validators;
434
            });
435
            var numValidators = 0;
436
            $.each(validators, function (i, el) {
437
              numValidators += el.length;
438
            });
439
            $this.bind("getValidatorCount.validation", function () {
440
              return numValidators;
441
            });
442
            $this.bind("submit.validation", function () {
443
              return $this.triggerHandler("change.validation", {
444
                submitting: true,
445
              });
446
            });
447
            $this.bind(
448
              (settings.options.bindEvents.length > 0
449
                ? settings.options.bindEvents
450
                : [
451
                    "keyup",
452
                    "focus",
453
                    "blur",
454
                    "click",
455
                    "keydown",
456
                    "keypress",
457
                    "change",
458
                  ]
459
              )
460
                .concat(["revalidate"])
461
                .join(".validation ") + ".validation",
462
              function (e, params) {
463
                var value = getValue($this);
464
                var errorsFound = [];
465
                if (params && !!params.submitting) {
466
                  $controlGroup.data("jqbvIsSubmitting", true);
467
                } else if (e.type !== "revalidate") {
468
                  $controlGroup.data("jqbvIsSubmitting", false);
469
                }
470
                var formIsSubmitting = !!$controlGroup.data("jqbvIsSubmitting");
471
                $controlGroup
472
                  .find("input,textarea,select")
473
                  .not("[type=submit]")
474
                  .each(function (i, el) {
475
                    var oldCount = errorsFound.length;
476
                    $.each(
477
                      $(el).triggerHandler("validation.validation", params) || [],
478
                      function (j, message) {
479
                        errorsFound.push(message);
480
                      }
481
                    );
482
                    if (errorsFound.length > oldCount) {
483
                      $(el).attr("aria-invalid", "true");
484
                    } else {
485
                      var original = $this.data("original-aria-invalid");
486
                      $(el).attr(
487
                        "aria-invalid",
488
                        original !== undefined ? original : false
489
                      );
490
                    }
491
                  });
492
                $form
493
                  .find("input,select,textarea")
494
                  .not($this)
495
                  .not('[name="' + $this.attr("name") + '"]')
496
                  .trigger("validationLostFocus.validation");
497
                errorsFound = $.unique(errorsFound.sort());
498
                if (errorsFound.length) {
499
                  $controlGroup
500
                    .removeClass("validate error issue")
501
                    .addClass(formIsSubmitting ? "error" : "issue");
502
                  if (
503
                    settings.options.semanticallyStrict &&
504
                    errorsFound.length === 1
505
                  ) {
506
                    $helpBlock.html(
507
                      errorsFound[0] +
508
                        (settings.options.prependExistingHelpBlock
509
                          ? $helpBlock.data("original-contents")
510
                          : "")
511
                    );
512
                  } else {
513
                    $helpBlock.html(
514
                      '<ul role="alert"><li>' +
515
                        errorsFound.join("</li><li>") +
516
                        "</li></ul>" +
517
                        (settings.options.prependExistingHelpBlock
518
                          ? $helpBlock.data("original-contents")
519
                          : "")
520
                    );
521
                  }
522
                } else {
523
                  $controlGroup.removeClass("issue error validate");
524
                  if (value.length > 0) {
525
                    $controlGroup.addClass("validate");
526
                  }
527
                  $helpBlock.html($helpBlock.data("original-contents"));
528
                }
529
                if (e.type === "blur") {
530
                  if (settings.options.removeSuccess) {
531
                  }
532
                }
533
              }
534
            );
535
            $this.bind("validationLostFocus.validation", function () {
536
              if (settings.options.removeSuccess) {
537
              }
538
            });
539
          });
540
        },
541
        destroy: function () {
542
          return this.each(function () {
543
            var $this = $(this),
544
              $controlGroup = $this.parents(".form-group").first(),
545
              $helpBlock = $controlGroup.find(".help-block").first(),
546
              $form = $this.parents("form").first();
547
            $this.unbind(".validation");
548
            $form.unbind(".validationSubmit");
549
            $helpBlock.html($helpBlock.data("original-contents"));
550
            $controlGroup.attr("class", $controlGroup.data("original-classes"));
551
            $this.attr("aria-invalid", $this.data("original-aria-invalid"));
552
            $helpBlock.attr("role", $this.data("original-role"));
553
            if ($.inArray($helpBlock[0], createdElements) > -1) {
554
              $helpBlock.remove();
555
            }
556
          });
557
        },
558
        collectErrors: function (includeEmpty) {
559
          var errorMessages = {};
560
          this.each(function (i, el) {
561
            var $el = $(el);
562
            var name = $el.attr("name");
563
            var errors = $el.triggerHandler("validation.validation", {
564
              includeEmpty: true,
565
            });
566
            errorMessages[name] = $.extend(true, errors, errorMessages[name]);
567
          });
568
          $.each(errorMessages, function (i, el) {
569
            if (el.length === 0) {
570
              delete errorMessages[i];
571
            }
572
          });
573
          return errorMessages;
574
        },
575
        hasErrors: function () {
576
          var errorMessages = [];
577
          this.find("input,select,textarea")
578
            .add(this)
579
            .each(function (i, el) {
580
              errorMessages = errorMessages.concat(
581
                $(el).triggerHandler("getValidators.validation")
582
                  ? $(el).triggerHandler("validation.validation", {
583
                      submitting: true,
584
                    })
585
                  : []
586
              );
587
            });
588
          return errorMessages.length > 0;
589
        },
590
        override: function (newDefaults) {
591
          defaults = $.extend(true, defaults, newDefaults);
592
        },
593
      },
594
      validatorTypes: {
595
        callback: {
596
          name: "callback",
597
          init: function ($this, name) {
598
            var result = {
599
              validatorName: name,
600
              callback: $this.data("validation" + name + "Callback"),
601
              lastValue: $this.val(),
602
              lastValid: true,
603
              lastFinished: true,
604
            };
605
            var message = "Not valid";
606
            if ($this.data("validation" + name + "Message")) {
607
              message = $this.data("validation" + name + "Message");
608
            }
609
            result.message = message;
610
            return result;
611
          },
612
          validate: function ($this, value, validator) {
613
            if (validator.lastValue === value && validator.lastFinished) {
614
              return !validator.lastValid;
615
            }
616
            if (validator.lastFinished === true) {
617
              validator.lastValue = value;
618
              validator.lastValid = true;
619
              validator.lastFinished = false;
620
              var rrjqbvValidator = validator;
621
              var rrjqbvThis = $this;
622
              executeFunctionByName(
623
                validator.callback,
624
                window,
625
                $this,
626
                value,
627
                function (data) {
628
                  if (rrjqbvValidator.lastValue === data.value) {
629
                    rrjqbvValidator.lastValid = data.valid;
630
                    if (data.message) {
631
                      rrjqbvValidator.message = data.message;
632
                    }
633
                    rrjqbvValidator.lastFinished = true;
634
                    rrjqbvThis.data(
635
                      "validation" + rrjqbvValidator.validatorName + "Message",
636
                      rrjqbvValidator.message
637
                    );
638
                    setTimeout(function () {
639
                      if (
640
                        !$this.is(":focus") &&
641
                        $this.parents("form").first().data("jqbvIsSubmitting")
642
                      ) {
643
                        rrjqbvThis.trigger("blur.validation");
644
                      } else {
645
                        rrjqbvThis.trigger("revalidate.validation");
646
                      }
647
                    }, 1);
648
                  }
649
                }
650
              );
651
            }
652
            return false;
653
          },
654
        },
655
        ajax: {
656
          name: "ajax",
657
          init: function ($this, name) {
658
            return {
659
              validatorName: name,
660
              url: $this.data("validation" + name + "Ajax"),
661
              lastValue: $this.val(),
662
              lastValid: true,
663
              lastFinished: true,
664
            };
665
          },
666
          validate: function ($this, value, validator) {
667
            if (
668
              "" + validator.lastValue === "" + value &&
669
              validator.lastFinished === true
670
            ) {
671
              return validator.lastValid === false;
672
            }
673
            if (validator.lastFinished === true) {
674
              validator.lastValue = value;
675
              validator.lastValid = true;
676
              validator.lastFinished = false;
677
              $.ajax({
678
                url: validator.url,
679
                data:
680
                  "value=" +
681
                  encodeURIComponent(value) +
682
                  "&field=" +
683
                  $this.attr("name"),
684
                dataType: "json",
685
                success: function (data) {
686
                  if ("" + validator.lastValue === "" + data.value) {
687
                    validator.lastValid = !!data.valid;
688
                    if (data.message) {
689
                      validator.message = data.message;
690
                    }
691
                    validator.lastFinished = true;
692
                    $this.data(
693
                      "validation" + validator.validatorName + "Message",
694
                      validator.message
695
                    );
696
                    setTimeout(function () {
697
                      $this.trigger("revalidate.validation");
698
                    }, 1);
699
                  }
700
                },
701
                failure: function () {
702
                  validator.lastValid = true;
703
                  validator.message = "ajax call failed";
704
                  validator.lastFinished = true;
705
                  $this.data(
706
                    "validation" + validator.validatorName + "Message",
707
                    validator.message
708
                  );
709
                  setTimeout(function () {
710
                    $this.trigger("revalidate.validation");
711
                  }, 1);
712
                },
713
              });
714
            }
715
            return false;
716
          },
717
        },
718
        regex: {
719
          name: "regex",
720
          init: function ($this, name) {
721
            var result = {};
722
            var regexString = $this.data("validation" + name + "Regex");
723
            result.regex = regexFromString(regexString);
724
            if (regexString === undefined) {
725
              $.error(
726
                "Can't find regex for '" +
727
                  name +
728
                  "' validator on '" +
729
                  $this.attr("name") +
730
                  "'"
731
              );
732
            }
733
            var message = "Not in the expected format";
734
            if ($this.data("validation" + name + "Message")) {
735
              message = $this.data("validation" + name + "Message");
736
            }
737
            result.message = message;
738
            result.originalName = name;
739
            return result;
740
          },
741
          validate: function ($this, value, validator) {
742
            return (
743
              (!validator.regex.test(value) && !validator.negative) ||
744
              (validator.regex.test(value) && validator.negative)
745
            );
746
          },
747
        },
748
        email: {
749
          name: "email",
750
          init: function ($this, name) {
751
            var result = {};
752
            result.regex = regexFromString(
753
              "[a-zA-Z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
754
            );
755
            var message = "Not a valid email address";
756
            if ($this.data("validation" + name + "Message")) {
757
              message = $this.data("validation" + name + "Message");
758
            }
759
            result.message = message;
760
            result.originalName = name;
761
            return result;
762
          },
763
          validate: function ($this, value, validator) {
764
            return (
765
              (!validator.regex.test(value) && !validator.negative) ||
766
              (validator.regex.test(value) && validator.negative)
767
            );
768
          },
769
        },
770
        required: {
771
          name: "required",
772
          init: function ($this, name) {
773
            var message = "This is required";
774
            if ($this.data("validation" + name + "Message")) {
775
              message = $this.data("validation" + name + "Message");
776
            }
777
            return {
778
              message: message,
779
              includeEmpty: true,
780
            };
781
          },
782
          validate: function ($this, value, validator) {
783
            return !!(
784
              (value.length === 0 && !validator.negative) ||
785
              (value.length > 0 && validator.negative)
786
            );
787
          },
788
          blockSubmit: true,
789
        },
790
        match: {
791
          name: "match",
792
          init: function ($this, name) {
793
            var elementName = $this.data("validation" + name + "Match");
794
            var $form = $this.parents("form").first();
795
            var $element = $form.find('[name="' + elementName + '"]').first();
796
            $element.bind("validation.validation", function () {
797
              $this.trigger("revalidate.validation", {
798
                submitting: true,
799
              });
800
            });
801
            var result = {};
802
            result.element = $element;
803
            if ($element.length === 0) {
804
              $.error(
805
                "Can't find field '" +
806
                  elementName +
807
                  "' to match '" +
808
                  $this.attr("name") +
809
                  "' against in '" +
810
                  name +
811
                  "' validator"
812
              );
813
            }
814
            var message = "Must match";
815
            var $label = null;
816
            if (
817
              ($label = $form.find('label[for="' + elementName + '"]')).length
818
            ) {
819
              message += " '" + $label.text() + "'";
820
            } else if (
821
              ($label = $element.parents(".form-group").first().find("label"))
822
                .length
823
            ) {
824
              message += " '" + $label.first().text() + "'";
825
            }
826
            if ($this.data("validation" + name + "Message")) {
827
              message = $this.data("validation" + name + "Message");
828
            }
829
            result.message = message;
830
            return result;
831
          },
832
          validate: function ($this, value, validator) {
833
            return (
834
              (value !== validator.element.val() && !validator.negative) ||
835
              (value === validator.element.val() && validator.negative)
836
            );
837
          },
838
          blockSubmit: true,
839
          includeEmpty: true,
840
        },
841
        max: {
842
          name: "max",
843
          init: function ($this, name) {
844
            var result = {};
845
            result.max = $this.data("validation" + name + "Max");
846
            result.message = "Too high: Maximum of '" + result.max + "'";
847
            if ($this.data("validation" + name + "Message")) {
848
              result.message = $this.data("validation" + name + "Message");
849
            }
850
            return result;
851
          },
852
          validate: function ($this, value, validator) {
853
            return (
854
              (parseFloat(value, 10) > parseFloat(validator.max, 10) &&
855
                !validator.negative) ||
856
              (parseFloat(value, 10) <= parseFloat(validator.max, 10) &&
857
                validator.negative)
858
            );
859
          },
860
        },
861
        min: {
862
          name: "min",
863
          init: function ($this, name) {
864
            var result = {};
865
            result.min = $this.data("validation" + name + "Min");
866
            result.message = "Too low: Minimum of '" + result.min + "'";
867
            if ($this.data("validation" + name + "Message")) {
868
              result.message = $this.data("validation" + name + "Message");
869
            }
870
            return result;
871
          },
872
          validate: function ($this, value, validator) {
873
            return (
874
              (parseFloat(value) < parseFloat(validator.min) &&
875
                !validator.negative) ||
876
              (parseFloat(value) >= parseFloat(validator.min) &&
877
                validator.negative)
878
            );
879
          },
880
        },
881
        maxlength: {
882
          name: "maxlength",
883
          init: function ($this, name) {
884
            var result = {};
885
            result.maxlength = $this.data("validation" + name + "Maxlength");
886
            result.message =
887
              "Too long: Maximum of '" + result.maxlength + "' characters";
888
            if ($this.data("validation" + name + "Message")) {
889
              result.message = $this.data("validation" + name + "Message");
890
            }
891
            return result;
892
          },
893
          validate: function ($this, value, validator) {
894
            return (
895
              (value.length > validator.maxlength && !validator.negative) ||
896
              (value.length <= validator.maxlength && validator.negative)
897
            );
898
          },
899
        },
900
        minlength: {
901
          name: "minlength",
902
          init: function ($this, name) {
903
            var result = {};
904
            result.minlength = $this.data("validation" + name + "Minlength");
905
            result.message =
906
              "Too short: Minimum of '" + result.minlength + "' characters";
907
            if ($this.data("validation" + name + "Message")) {
908
              result.message = $this.data("validation" + name + "Message");
909
            }
910
            return result;
911
          },
912
          validate: function ($this, value, validator) {
913
            return (
914
              (value.length < validator.minlength && !validator.negative) ||
915
              (value.length >= validator.minlength && validator.negative)
916
            );
917
          },
918
        },
919
        maxchecked: {
920
          name: "maxchecked",
921
          init: function ($this, name) {
922
            var result = {};
923
            var elements = $this
924
              .parents("form")
925
              .first()
926
              .find('[name="' + $this.attr("name") + '"]');
927
            elements.bind("change.validation click.validation", function () {
928
              $this.trigger("revalidate.validation", {
929
                includeEmpty: true,
930
              });
931
            });
932
            result.elements = elements;
933
            result.maxchecked = $this.data("validation" + name + "Maxchecked");
934
            var message = "Too many: Max '" + result.maxchecked + "' checked";
935
            if ($this.data("validation" + name + "Message")) {
936
              message = $this.data("validation" + name + "Message");
937
            }
938
            result.message = message;
939
            return result;
940
          },
941
          validate: function ($this, value, validator) {
942
            return (
943
              (validator.elements.filter(":checked").length >
944
                validator.maxchecked &&
945
                !validator.negative) ||
946
              (validator.elements.filter(":checked").length <=
947
                validator.maxchecked &&
948
                validator.negative)
949
            );
950
          },
951
          blockSubmit: true,
952
        },
953
        minchecked: {
954
          name: "minchecked",
955
          init: function ($this, name) {
956
            var result = {};
957
            var elements = $this
958
              .parents("form")
959
              .first()
960
              .find('[name="' + $this.attr("name") + '"]');
961
            elements.bind("change.validation click.validation", function () {
962
              $this.trigger("revalidate.validation", {
963
                includeEmpty: true,
964
              });
965
            });
966
            result.elements = elements;
967
            result.minchecked = $this.data("validation" + name + "Minchecked");
968
            var message = "Too few: Min '" + result.minchecked + "' checked";
969
            if ($this.data("validation" + name + "Message")) {
970
              message = $this.data("validation" + name + "Message");
971
            }
972
            result.message = message;
973
            return result;
974
          },
975
          validate: function ($this, value, validator) {
976
            return (
977
              (validator.elements.filter(":checked").length <
978
                validator.minchecked &&
979
                !validator.negative) ||
980
              (validator.elements.filter(":checked").length >=
981
                validator.minchecked &&
982
                validator.negative)
983
            );
984
          },
985
          blockSubmit: true,
986
          includeEmpty: true,
987
        },
988
        number: {
989
          name: "number",
990
          init: function ($this, name) {
991
            var result = {};
992
            result.step = 1;
993
            if ($this.attr("step")) {
994
              result.step = $this.attr("step");
995
            }
996
            if ($this.data("validation" + name + "Step")) {
997
              result.step = $this.data("validation" + name + "Step");
998
            }
999
            result.decimal = ".";
1000
            if ($this.data("validation" + name + "Decimal")) {
1001
              result.decimal = $this.data("validation" + name + "Decimal");
1002
            }
1003
            result.thousands = "";
1004
            if ($this.data("validation" + name + "Thousands")) {
1005
              result.thousands = $this.data("validation" + name + "Thousands");
1006
            }
1007
            result.regex = regexFromString(
1008
              "([+-]?\\d+(\\" + result.decimal + "\\d+)?)?"
1009
            );
1010
            result.message = "Must be a number";
1011
            var dataMessage = $this.data("validation" + name + "Message");
1012
            if (dataMessage) {
1013
              result.message = dataMessage;
1014
            }
1015
            return result;
1016
          },
1017
          validate: function ($this, value, validator) {
1018
            var globalValue = value
1019
              .replace(validator.decimal, ".")
1020
              .replace(validator.thousands, "");
1021
            var multipliedValue = parseFloat(globalValue);
1022
            var multipliedStep = parseFloat(validator.step);
1023
            while (multipliedStep % 1 !== 0) {
1024
              multipliedStep = parseFloat(multipliedStep.toPrecision(12)) * 10;
1025
              multipliedValue = parseFloat(multipliedValue.toPrecision(12)) * 10;
1026
            }
1027
            var regexResult = validator.regex.test(value);
1028
            var stepResult =
1029
              parseFloat(multipliedValue) % parseFloat(multipliedStep) === 0;
1030
            var typeResult =
1031
              !isNaN(parseFloat(globalValue)) && isFinite(globalValue);
1032
            var result = !(regexResult && stepResult && typeResult);
1033
            return result;
1034
          },
1035
          message: "Must be a number",
1036
        },
1037
      },
1038
      builtInValidators: {
1039
        email: {
1040
          name: "Email",
1041
          type: "email",
1042
        },
1043
        passwordagain: {
1044
          name: "Passwordagain",
1045
          type: "match",
1046
          match: "password",
1047
          message:
1048
            "Does not match the given password<!-- data-validator-paswordagain-message to override -->",
1049
        },
1050
        positive: {
1051
          name: "Positive",
1052
          type: "shortcut",
1053
          shortcut: "number,positivenumber",
1054
        },
1055
        negative: {
1056
          name: "Negative",
1057
          type: "shortcut",
1058
          shortcut: "number,negativenumber",
1059
        },
1060
        integer: {
1061
          name: "Integer",
1062
          type: "regex",
1063
          regex: "[+-]?\\d+",
1064
          message:
1065
            "No decimal places allowed<!-- data-validator-integer-message to override -->",
1066
        },
1067
        positivenumber: {
1068
          name: "Positivenumber",
1069
          type: "min",
1070
          min: 0,
1071
          message:
1072
            "Must be a positive number<!-- data-validator-positivenumber-message to override -->",
1073
        },
1074
        negativenumber: {
1075
          name: "Negativenumber",
1076
          type: "max",
1077
          max: 0,
1078
          message:
1079
            "Must be a negative number<!-- data-validator-negativenumber-message to override -->",
1080
        },
1081
        required: {
1082
          name: "Required",
1083
          type: "required",
1084
          message:
1085
            "This is required<!-- data-validator-required-message to override -->",
1086
        },
1087
        checkone: {
1088
          name: "Checkone",
1089
          type: "minchecked",
1090
          minchecked: 1,
1091
          message:
1092
            "Check at least one option<!-- data-validation-checkone-message to override -->",
1093
        },
1094
        number: {
1095
          name: "Number",
1096
          type: "number",
1097
          decimal: ".",
1098
          step: "1",
1099
        },
1100
        pattern: {
1101
          name: "Pattern",
1102
          type: "regex",
1103
          message: "Not in expected format",
1104
        },
1105
      },
1106
    };
1107
    var formatValidatorName = function (name) {
1108
      return name.toLowerCase().replace(/(^|\s)([a-z])/g, function (m, p1, p2) {
1109
        return p1 + p2.toUpperCase();
1110
      });
1111
    };
1112
    var getValue = function ($this) {
1113
      var value = null;
1114
      var type = $this.attr("type");
1115
      if (type === "checkbox") {
1116
        value = $this.is(":checked") ? value : "";
1117
        var checkboxParent =
1118
          $this.parents("form").first() || $this.parents(".form-group").first();
1119
        if (checkboxParent) {
1120
          value = checkboxParent
1121
            .find("input[name='" + $this.attr("name") + "']:checked")
1122
            .map(function (i, el) {
1123
              return $(el).val();
1124
            })
1125
            .toArray()
1126
            .join(",");
1127
        }
1128
      } else if (type === "radio") {
1129
        value =
1130
          $('input[name="' + $this.attr("name") + '"]:checked').length > 0
1131
            ? $this.val()
1132
            : "";
1133
        var radioParent =
1134
          $this.parents("form").first() || $this.parents(".form-group").first();
1135
        if (radioParent) {
1136
          value = radioParent
1137
            .find("input[name='" + $this.attr("name") + "']:checked")
1138
            .map(function (i, el) {
1139
              return $(el).val();
1140
            })
1141
            .toArray()
1142
            .join(",");
1143
        }
1144
      } else if (type === "number") {
1145
        if ($this[0].validity.valid) {
1146
          value = $this.val();
1147
        } else {
1148
          if ($this[0].validity.badInput || $this[0].validity.stepMismatch) {
1149
            value = "NaN";
1150
          } else {
1151
            value = "";
1152
          }
1153
        }
1154
      } else {
1155
        value = $this.val();
1156
      }
1157
      return value;
1158
    };
1159
  
1160
    function regexFromString(inputstring) {
1161
      return new RegExp("^" + inputstring + "$");
1162
    }
1163
    /**
1164
     * Thanks to Jason Bunting via StackOverflow.com
1165
     *
1166
     * http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string#answer-359910
1167
     * Short link: http://tinyurl.com/executeFunctionByName
1168
     **/
1169
    function executeFunctionByName(functionName, context) {
1170
      var args = Array.prototype.slice.call(arguments, 2);
1171
      var namespaces = functionName.split(".");
1172
      var func = namespaces.pop();
1173
      for (var i = 0; i < namespaces.length; i++) {
1174
        context = context[namespaces[i]];
1175
      }
1176
      return context[func].apply(context, args);
1177
    }
1178
    $.fn.jqBootstrapValidation = function (method) {
1179
      if (defaults.methods[method]) {
1180
        return defaults.methods[method].apply(
1181
          this,
1182
          Array.prototype.slice.call(arguments, 1)
1183
        );
1184
      } else if (typeof method === "object" || !method) {
1185
        return defaults.methods.init.apply(this, arguments);
1186
      } else {
1187
        $.error(
1188
          "Method " + method + " does not exist on jQuery.jqBootstrapValidation"
1189
        );
1190
        return null;
1191
      }
1192
    };
1193
    $.jqBootstrapValidation = function (options) {
1194
      $(":input")
1195
        .not("[type=image],[type=submit]")
1196
        .jqBootstrapValidation.apply(this, arguments);
1197
    };
1198
  })(jQuery);

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.