corrade-nucleus-nucleons – Blame information for rev 20

Subversion Repositories:
Rev:
Rev Author Line No. Line
20 office 1 /* ========================================================================
2 * Bootstrap (plugin): validator.js v0.11.9
3 * ========================================================================
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2016 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 $el.is('select[multiple]') ? ($el.val() || []).length :
39 $el.val()
40 }
41  
42 var Validator = function (element, options) {
43 this.options = options
44 this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
45 this.$element = $(element)
46 this.$btn = $('button[type="submit"], input[type="submit"]')
47 .filter('[form="' + this.$element.attr('id') + '"]')
48 .add(this.$element.find('input[type="submit"], button[type="submit"]'))
49  
50 this.update()
51  
52 this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
53 this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
54 this.$element.on('reset.bs.validator', $.proxy(this.reset, this))
55  
56 this.$element.find('[data-match]').each(function () {
57 var $this = $(this)
58 var target = $this.attr('data-match')
59  
60 $(target).on('input.bs.validator', function (e) {
61 getValue($this) && $this.trigger('input.bs.validator')
62 })
63 })
64  
65 // run validators for fields with values, but don't clobber server-side errors
66 this.$inputs.filter(function () {
67 return getValue($(this)) && !$(this).closest('.has-error').length
68 }).trigger('focusout')
69  
70 this.$element.attr('novalidate', true) // disable automatic native validation
71 }
72  
73 Validator.VERSION = '0.11.9'
74  
75 Validator.INPUT_SELECTOR = ':input:not([type="hidden"], [type="submit"], [type="reset"], button)'
76  
77 Validator.FOCUS_OFFSET = 20
78  
79 Validator.DEFAULTS = {
80 delay: 500,
81 html: false,
82 disable: true,
83 focus: true,
84 custom: {},
85 errors: {
86 match: 'Does not match',
87 minlength: 'Not long enough'
88 },
89 feedback: {
90 success: 'glyphicon-ok',
91 error: 'glyphicon-remove'
92 }
93 }
94  
95 Validator.VALIDATORS = {
96 'native': function ($el) {
97 var el = $el[0]
98 if (el.checkValidity) {
99 return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!")
100 }
101 },
102 'match': function ($el) {
103 var target = $el.attr('data-match')
104 return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match
105 },
106 'minlength': function ($el) {
107 var minlength = $el.attr('data-minlength')
108 return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength
109 }
110 }
111  
112 Validator.prototype.update = function () {
113 var self = this
114  
115 this.$inputs = this.$element.find(Validator.INPUT_SELECTOR)
116 .add(this.$element.find('[data-validate="true"]'))
117 .not(this.$element.find('[data-validate="false"]')
118 .each(function () { self.clearErrors($(this)) })
119 )
120  
121 this.toggleSubmit()
122  
123 return this
124 }
125  
126 Validator.prototype.onInput = function (e) {
127 var self = this
128 var $el = $(e.target)
129 var deferErrors = e.type !== 'focusout'
130  
131 if (!this.$inputs.is($el)) return
132  
133 this.validateInput($el, deferErrors).done(function () {
134 self.toggleSubmit()
135 })
136 }
137  
138 Validator.prototype.validateInput = function ($el, deferErrors) {
139 var value = getValue($el)
140 var prevErrors = $el.data('bs.validator.errors')
141  
142 if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
143  
144 var e = $.Event('validate.bs.validator', {relatedTarget: $el[0]})
145 this.$element.trigger(e)
146 if (e.isDefaultPrevented()) return
147  
148 var self = this
149  
150 return this.runValidators($el).done(function (errors) {
151 $el.data('bs.validator.errors', errors)
152  
153 errors.length
154 ? deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el)
155 : self.clearErrors($el)
156  
157 if (!prevErrors || errors.toString() !== prevErrors.toString()) {
158 e = errors.length
159 ? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
160 : $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
161  
162 self.$element.trigger(e)
163 }
164  
165 self.toggleSubmit()
166  
167 self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
168 })
169 }
170  
171  
172 Validator.prototype.runValidators = function ($el) {
173 var errors = []
174 var deferred = $.Deferred()
175  
176 $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
177 $el.data('bs.validator.deferred', deferred)
178  
179 function getValidatorSpecificError(key) {
180 return $el.attr('data-' + key + '-error')
181 }
182  
183 function getValidityStateError() {
184 var validity = $el[0].validity
185 return validity.typeMismatch ? $el.attr('data-type-error')
186 : validity.patternMismatch ? $el.attr('data-pattern-error')
187 : validity.stepMismatch ? $el.attr('data-step-error')
188 : validity.rangeOverflow ? $el.attr('data-max-error')
189 : validity.rangeUnderflow ? $el.attr('data-min-error')
190 : validity.valueMissing ? $el.attr('data-required-error')
191 : null
192 }
193  
194 function getGenericError() {
195 return $el.attr('data-error')
196 }
197  
198 function getErrorMessage(key) {
199 return getValidatorSpecificError(key)
200 || getValidityStateError()
201 || getGenericError()
202 }
203  
204 $.each(this.validators, $.proxy(function (key, validator) {
205 var error = null
206 if ((getValue($el) || $el.attr('required')) &&
207 ($el.attr('data-' + key) !== undefined || key == 'native') &&
208 (error = validator.call(this, $el))) {
209 error = getErrorMessage(key) || error
210 !~errors.indexOf(error) && errors.push(error)
211 }
212 }, this))
213  
214 if (!errors.length && getValue($el) && $el.attr('data-remote')) {
215 this.defer($el, function () {
216 var data = {}
217 data[$el.attr('name')] = getValue($el)
218 $.get($el.attr('data-remote'), data)
219 .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
220 .always(function () { deferred.resolve(errors)})
221 })
222 } else deferred.resolve(errors)
223  
224 return deferred.promise()
225 }
226  
227 Validator.prototype.validate = function () {
228 var self = this
229  
230 $.when(this.$inputs.map(function (el) {
231 return self.validateInput($(this), false)
232 })).then(function () {
233 self.toggleSubmit()
234 self.focusError()
235 })
236  
237 return this
238 }
239  
240 Validator.prototype.focusError = function () {
241 if (!this.options.focus) return
242  
243 var $input = this.$element.find(".has-error:first :input")
244 if ($input.length === 0) return
245  
246 $('html, body').animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250)
247 $input.focus()
248 }
249  
250 Validator.prototype.showErrors = function ($el) {
251 var method = this.options.html ? 'html' : 'text'
252 var errors = $el.data('bs.validator.errors')
253 var $group = $el.closest('.form-group')
254 var $block = $group.find('.help-block.with-errors')
255 var $feedback = $group.find('.form-control-feedback')
256  
257 if (!errors.length) return
258  
259 errors = $('<ul/>')
260 .addClass('list-unstyled')
261 .append($.map(errors, function (error) { return $('<li/>')[method](error) }))
262  
263 $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
264 $block.empty().append(errors)
265 $group.addClass('has-error has-danger')
266  
267 $group.hasClass('has-feedback')
268 && $feedback.removeClass(this.options.feedback.success)
269 && $feedback.addClass(this.options.feedback.error)
270 && $group.removeClass('has-success')
271 }
272  
273 Validator.prototype.clearErrors = function ($el) {
274 var $group = $el.closest('.form-group')
275 var $block = $group.find('.help-block.with-errors')
276 var $feedback = $group.find('.form-control-feedback')
277  
278 $block.html($block.data('bs.validator.originalContent'))
279 $group.removeClass('has-error has-danger has-success')
280  
281 $group.hasClass('has-feedback')
282 && $feedback.removeClass(this.options.feedback.error)
283 && $feedback.removeClass(this.options.feedback.success)
284 && getValue($el)
285 && $feedback.addClass(this.options.feedback.success)
286 && $group.addClass('has-success')
287 }
288  
289 Validator.prototype.hasErrors = function () {
290 function fieldErrors() {
291 return !!($(this).data('bs.validator.errors') || []).length
292 }
293  
294 return !!this.$inputs.filter(fieldErrors).length
295 }
296  
297 Validator.prototype.isIncomplete = function () {
298 function fieldIncomplete() {
299 var value = getValue($(this))
300 return !(typeof value == "string" ? $.trim(value) : value)
301 }
302  
303 return !!this.$inputs.filter('[required]').filter(fieldIncomplete).length
304 }
305  
306 Validator.prototype.onSubmit = function (e) {
307 this.validate()
308 if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
309 }
310  
311 Validator.prototype.toggleSubmit = function () {
312 if (!this.options.disable) return
313 this.$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
314 }
315  
316 Validator.prototype.defer = function ($el, callback) {
317 callback = $.proxy(callback, this, $el)
318 if (!this.options.delay) return callback()
319 window.clearTimeout($el.data('bs.validator.timeout'))
320 $el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
321 }
322  
323 Validator.prototype.reset = function () {
324 this.$element.find('.form-control-feedback')
325 .removeClass(this.options.feedback.error)
326 .removeClass(this.options.feedback.success)
327  
328 this.$inputs
329 .removeData(['bs.validator.errors', 'bs.validator.deferred'])
330 .each(function () {
331 var $this = $(this)
332 var timeout = $this.data('bs.validator.timeout')
333 window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
334 })
335  
336 this.$element.find('.help-block.with-errors')
337 .each(function () {
338 var $this = $(this)
339 var originalContent = $this.data('bs.validator.originalContent')
340  
341 $this
342 .removeData('bs.validator.originalContent')
343 .html(originalContent)
344 })
345  
346 this.$btn.removeClass('disabled')
347  
348 this.$element.find('.has-error, .has-danger, .has-success').removeClass('has-error has-danger has-success')
349  
350 return this
351 }
352  
353 Validator.prototype.destroy = function () {
354 this.reset()
355  
356 this.$element
357 .removeAttr('novalidate')
358 .removeData('bs.validator')
359 .off('.bs.validator')
360  
361 this.$inputs
362 .off('.bs.validator')
363  
364 this.options = null
365 this.validators = null
366 this.$element = null
367 this.$btn = null
368 this.$inputs = null
369  
370 return this
371 }
372  
373 // VALIDATOR PLUGIN DEFINITION
374 // ===========================
375  
376  
377 function Plugin(option) {
378 return this.each(function () {
379 var $this = $(this)
380 var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
381 var data = $this.data('bs.validator')
382  
383 if (!data && option == 'destroy') return
384 if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
385 if (typeof option == 'string') data[option]()
386 })
387 }
388  
389 var old = $.fn.validator
390  
391 $.fn.validator = Plugin
392 $.fn.validator.Constructor = Validator
393  
394  
395 // VALIDATOR NO CONFLICT
396 // =====================
397  
398 $.fn.validator.noConflict = function () {
399 $.fn.validator = old
400 return this
401 }
402  
403  
404 // VALIDATOR DATA-API
405 // ==================
406  
407 $(window).on('load', function () {
408 $('form[data-toggle="validator"]').each(function () {
409 var $form = $(this)
410 Plugin.call($form, $form.data())
411 })
412 })
413  
414 }(jQuery);