PageSourceSearch

https://nlsa.ca/cloud/global/js/validator.js

js nlsa.ca collected 2026-10-02 22:55:31 UTC 11,869 bytes, 361 lines download raw bytes

1/* ========================================================================
2 * Bootstrap (plugin): validator.js v0.10.2
3 * ========================================================================
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2015 Cina Saffary.
7 * Made by @1000hz in the style of Bootstrap 3 era @fat
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 * ======================================================================== */
27
28
29+function ($) {
30  'use strict';
31
32  // VALIDATOR CLASS DEFINITION
33  // ==========================
34
35  function getValue($el) {
36    return $el.is('[type="checkbox"]') ? $el.prop('checked')                                     :
37           $el.is('[type="radio"]')    ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
38                                         $.trim($el.val())
39  }
40
41  var Validator = function (element, options) {
42    this.options  = options
43    this.$element = $(element)
44    this.$inputs  = this.$element.find(Validator.INPUT_SELECTOR)
45    this.$btn     = $('button[type="submit"], input[type="submit"]')
46                      .filter('[form="' + this.$element.attr('id') + '"]')
47                      .add(this.$element.find('input[type="submit"], button[type="submit"]'))
48
49    options.errors = $.extend({}, Validator.DEFAULTS.errors, options.errors)
50
51    for (var custom in options.custom) {
52      if (!options.errors[custom]) throw new Error('Missing default error message for custom validator: ' + custom)
53    }
54
55    $.extend(Validator.VALIDATORS, options.custom)
56
57    this.$element.attr('novalidate', true) // disable automatic native validation
58    this.toggleSubmit()
59
60    this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', Validator.INPUT_SELECTOR, $.proxy(this.onInput, this))
61    this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
62
63    this.$element.find('[data-match]').each(function () {
64      var $this  = $(this)
65      var target = $this.data('match')
66
67      $(target).on('input.bs.validator', function (e) {
68        getValue($this) && $this.trigger('input.bs.validator')
69      })
70    })
71  }
72
73  Validator.INPUT_SELECTOR = ':input:not([type="submit"], button):enabled:visible'
74
75  Validator.FOCUS_OFFSET = 20
76
77  Validator.DEFAULTS = {
78    delay: 500,
79    html: false,
80    disable: true,
81    focus: true,
82    custom: {},
83    errors: {
84      match: 'Does not match',
85      minlength: 'Not long enough'
86    },
87    feedback: {
88      success: 'glyphicon-ok',
89      error: 'glyphicon-remove'
90    }
91  }
92
93  Validator.VALIDATORS = {
94    'native': function ($el) {
95      var el = $el[0]
96      return el.checkValidity ? el.checkValidity() : true
97    },
98    'match': function ($el) {
99      var target = $el.data('match')
100      return !$el.val() || $el.val() === $(target).val()
101    },
102    'minlength': function ($el) {
103      var minlength = $el.data('minlength')
104      return !$el.val() || $el.val().length >= minlength
105    }
106  }
107
108  Validator.prototype.onInput = function (e) {
109    var self        = this
110    var $el         = $(e.target)
111    var deferErrors = e.type !== 'focusout'
112    this.validateInput($el, deferErrors).done(function () {
113      self.toggleSubmit()
114    })
115  }
116
117  Validator.prototype.validateInput = function ($el, deferErrors) {
118    var value      = getValue($el)
119    var prevValue  = $el.data('bs.validator.previous')
120    var prevErrors = $el.data('bs.validator.errors')
121    var errors
122
123    if (prevValue === value) return $.Deferred().resolve()
124    else $el.data('bs.validator.previous', value)
125
126    if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
127
128    var e = $.Event('validate.bs.validator', {relatedTarget: $el[0]})
129    this.$element.trigger(e)
130    if (e.isDefaultPrevented()) return
131
132    var self = this
133
134    return this.runValidators($el).done(function (errors) {
135      $el.data('bs.validator.errors', errors)
136
137      errors.length
138        ? deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el)
139        : self.clearErrors($el)
140
141      if (!prevErrors || errors.toString() !== prevErrors.toString()) {
142        e = errors.length
143          ? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
144          : $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
145
146        self.$element.trigger(e)
147      }
148
149      self.toggleSubmit()
150
151      self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
152    })
153  }
154
155
156  Validator.prototype.runValidators = function ($el) {
157    var errors   = []
158    var deferred = $.Deferred()
159    var options  = this.options
160
161    $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
162    $el.data('bs.validator.deferred', deferred)
163
164    function getErrorMessage(key) {
165      return $el.data(key + '-error')
166        || $el.data('error')
167        || key == 'native' && $el[0].validationMessage
168        || options.errors[key]
169    }
170
171    $.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
172      if ((getValue($el) || $el.attr('required')) &&
173          ($el.data(key) || key == 'native') &&
174          !validator.call(this, $el)) {
175        var error = getErrorMessage(key)
176        !~errors.indexOf(error) && errors.push(error)
177      }
178    }, this))
179
180    if (!errors.length && getValue($el) && $el.data('remote')) {
181      this.defer($el, function () {
182        var data = {}
183        data[$el.attr('name')] = getValue($el)
184        $.get($el.data('remote'), data)
185          .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
186          .always(function () { deferred.resolve(errors)})
187      })
188    } else deferred.resolve(errors)
189
190    return deferred.promise()
191  }
192
193  Validator.prototype.validate = function () {
194    var self = this
195
196    $.when(this.$inputs.map(function (el) {
197      return self.validateInput($(this), false)
198    })).then(function () {
199      self.toggleSubmit()
200      self.focusError()
201    })
202
203    return this
204  }
205
206  Validator.prototype.focusError = function () {
207    if (!this.options.focus) return
208
209    var $input = $(".has-error:first :input")
210    if ($input.length === 0) return
211
212    $(document.body).animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250)
213    $input.focus()
214  }
215
216  Validator.prototype.showErrors = function ($el) {
217    var method = this.options.html ? 'html' : 'text'
218    var errors = $el.data('bs.validator.errors')
219    var $group = $el.closest('.form-group')
220    var $block = $group.find('.help-block.with-errors')
221    var $feedback = $group.find('.form-control-feedback')
222
223    if (!errors.length) return
224
225    errors = $('<ul/>')
226      .addClass('list-unstyled')
227      .append($.map(errors, function (error) { return $('<li/>')[method](error) }))
228
229    $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
230    $block.empty().append(errors)
231    $group.addClass('has-error has-danger')
232
233    $group.hasClass('has-feedback')
234      && $feedback.removeClass(this.options.feedback.success)
235      && $feedback.addClass(this.options.feedback.error)
236      && $group.removeClass('has-success')
237  }
238
239  Validator.prototype.clearErrors = function ($el) {
240    var $group = $el.closest('.form-group')
241    var $block = $group.find('.help-block.with-errors')
242    var $feedback = $group.find('.form-control-feedback')
243
244    $block.html($block.data('bs.validator.originalContent'))
245    $group.removeClass('has-error has-danger')
246
247    $group.hasClass('has-feedback')
248      && $feedback.removeClass(this.options.feedback.error)
249      && getValue($el)
250      && $feedback.addClass(this.options.feedback.success)
251      && $group.addClass('has-success')
252  }
253
254  Validator.prototype.hasErrors = function () {
255    function fieldErrors() {
256      return !!($(this).data('bs.validator.errors') || []).length
257    }
258
259    return !!this.$inputs.filter(fieldErrors).length
260  }
261
262  Validator.prototype.isIncomplete = function () {
263    function fieldIncomplete() {
264      return !getValue($(this))
265    }
266
267    return !!this.$inputs.filter('[required]').filter(fieldIncomplete).length
268  }
269
270  Validator.prototype.onSubmit = function (e) {
271    this.validate()
272    if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
273  }
274
275  Validator.prototype.toggleSubmit = function () {
276    if (!this.options.disable) return
277    this.$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
278  }
279
280  Validator.prototype.defer = function ($el, callback) {
281    callback = $.proxy(callback, this, $el)
282    if (!this.options.delay) return callback()
283    window.clearTimeout($el.data('bs.validator.timeout'))
284    $el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
285  }
286
287  Validator.prototype.destroy = function () {
288    this.$element
289      .removeAttr('novalidate')
290      .removeData('bs.validator')
291      .off('.bs.validator')
292      .find('.form-control-feedback')
293        .removeClass([this.options.feedback.error, this.options.feedback.success].join(' '))
294
295    this.$inputs
296      .off('.bs.validator')
297      .removeData(['bs.validator.errors', 'bs.validator.deferred', 'bs.validator.previous'])
298      .each(function () {
299        var $this = $(this)
300        var timeout = $this.data('bs.validator.timeout')
301        window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
302      })
303
304    this.$element.find('.help-block.with-errors').each(function () {
305      var $this = $(this)
306      var originalContent = $this.data('bs.validator.originalContent')
307
308      $this
309        .removeData('bs.validator.originalContent')
310        .html(originalContent)
311    })
312
313    this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')
314
315    this.$element.find('.has-error, .has-danger').removeClass('has-error has-danger')
316
317    return this
318  }
319
320  // VALIDATOR PLUGIN DEFINITION
321  // ===========================
322
323
324  function Plugin(option) {
325    return this.each(function () {
326      var $this   = $(this)
327      var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
328      var data    = $this.data('bs.validator')
329
330      if (!data && option == 'destroy') return
331      if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
332      if (typeof option == 'string') data[option]()
333    })
334  }
335
336  var old = $.fn.validator
337
338  $.fn.validator             = Plugin
339  $.fn.validator.Constructor = Validator
340
341
342  // VALIDATOR NO CONFLICT
343  // =====================
344
345  $.fn.validator.noConflict = function () {
346    $.fn.validator = old
347    return this
348  }
349
350
351  // VALIDATOR DATA-API
352  // ==================
353
354  $(window).on('load', function () {
355    $('form[data-toggle="validator"]').each(function () {
356      var $form = $(this)
357      Plugin.call($form, $form.data())
358    })
359  })
360
361}(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.