validator.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. +function ($) {
  28. 'use strict';
  29. // VALIDATOR CLASS DEFINITION
  30. // ==========================
  31. function getValue($el) {
  32. return $el.is('[type="checkbox"]') ? $el.prop('checked') :
  33. $el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length :
  34. $el.is('select[multiple]') ? ($el.val() || []).length :
  35. $el.val()
  36. }
  37. var Validator = function (element, options) {
  38. this.options = options
  39. this.validators = $.extend({}, Validator.VALIDATORS, options.custom)
  40. this.$element = $(element)
  41. this.$btn = $('button[type="submit"], input[type="submit"]')
  42. .filter('[form="' + this.$element.attr('id') + '"]')
  43. .add(this.$element.find('input[type="submit"], button[type="submit"]'))
  44. this.update()
  45. this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this))
  46. this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
  47. this.$element.on('reset.bs.validator', $.proxy(this.reset, this))
  48. this.$element.find('[data-match]').each(function () {
  49. var $this = $(this)
  50. var target = $this.attr('data-match')
  51. $(target).on('input.bs.validator', function (e) {
  52. getValue($this) && $this.trigger('input.bs.validator')
  53. })
  54. })
  55. // run validators for fields with values, but don't clobber server-side errors
  56. this.$inputs.filter(function () {
  57. return getValue($(this)) && !$(this).closest('.has-error').length
  58. }).trigger('focusout')
  59. this.$element.attr('novalidate', true) // disable automatic native validation
  60. }
  61. Validator.VERSION = '0.11.9'
  62. Validator.INPUT_SELECTOR = ':input:not([type="hidden"], [type="submit"], [type="reset"], button)'
  63. Validator.FOCUS_OFFSET = 20
  64. Validator.DEFAULTS = {
  65. delay: 500,
  66. html: false,
  67. disable: true,
  68. focus: true,
  69. custom: {},
  70. errors: {
  71. match: 'Does not match',
  72. minlength: 'Not long enough'
  73. },
  74. feedback: {
  75. success: 'glyphicon-ok',
  76. error: 'glyphicon-remove'
  77. }
  78. }
  79. Validator.VALIDATORS = {
  80. 'native': function ($el) {
  81. var el = $el[0]
  82. if (el.checkValidity) {
  83. return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!")
  84. }
  85. },
  86. 'match': function ($el) {
  87. var target = $el.attr('data-match')
  88. return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match
  89. },
  90. 'minlength': function ($el) {
  91. var minlength = $el.attr('data-minlength')
  92. return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength
  93. }
  94. }
  95. Validator.prototype.update = function () {
  96. var self = this
  97. this.$inputs = this.$element.find(Validator.INPUT_SELECTOR)
  98. .add(this.$element.find('[data-validate="true"]'))
  99. .not(this.$element.find('[data-validate="false"]')
  100. .each(function () { self.clearErrors($(this)) })
  101. )
  102. this.toggleSubmit()
  103. return this
  104. }
  105. Validator.prototype.onInput = function (e) {
  106. var self = this
  107. var $el = $(e.target)
  108. var deferErrors = e.type !== 'focusout'
  109. if (!this.$inputs.is($el)) return
  110. this.validateInput($el, deferErrors).done(function () {
  111. self.toggleSubmit()
  112. })
  113. }
  114. Validator.prototype.validateInput = function ($el, deferErrors) {
  115. var value = getValue($el)
  116. var prevErrors = $el.data('bs.validator.errors')
  117. if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
  118. var e = $.Event('validate.bs.validator', {relatedTarget: $el[0]})
  119. this.$element.trigger(e)
  120. if (e.isDefaultPrevented()) return
  121. var self = this
  122. return this.runValidators($el).done(function (errors) {
  123. $el.data('bs.validator.errors', errors)
  124. errors.length
  125. ? deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el)
  126. : self.clearErrors($el)
  127. if (!prevErrors || errors.toString() !== prevErrors.toString()) {
  128. e = errors.length
  129. ? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
  130. : $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
  131. self.$element.trigger(e)
  132. }
  133. self.toggleSubmit()
  134. self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
  135. })
  136. }
  137. Validator.prototype.runValidators = function ($el) {
  138. var errors = []
  139. var deferred = $.Deferred()
  140. $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
  141. $el.data('bs.validator.deferred', deferred)
  142. function getValidatorSpecificError(key) {
  143. return $el.attr('data-' + key + '-error')
  144. }
  145. function getValidityStateError() {
  146. var validity = $el[0].validity
  147. return validity.typeMismatch ? $el.attr('data-type-error')
  148. : validity.patternMismatch ? $el.attr('data-pattern-error')
  149. : validity.stepMismatch ? $el.attr('data-step-error')
  150. : validity.rangeOverflow ? $el.attr('data-max-error')
  151. : validity.rangeUnderflow ? $el.attr('data-min-error')
  152. : validity.valueMissing ? $el.attr('data-required-error')
  153. : null
  154. }
  155. function getGenericError() {
  156. return $el.attr('data-error')
  157. }
  158. function getErrorMessage(key) {
  159. return getValidatorSpecificError(key)
  160. || getValidityStateError()
  161. || getGenericError()
  162. }
  163. $.each(this.validators, $.proxy(function (key, validator) {
  164. var error = null
  165. if ((getValue($el) || $el.attr('required')) &&
  166. ($el.attr('data-' + key) !== undefined || key == 'native') &&
  167. (error = validator.call(this, $el))) {
  168. error = getErrorMessage(key) || error
  169. !~errors.indexOf(error) && errors.push(error)
  170. }
  171. }, this))
  172. if (!errors.length && getValue($el) && $el.attr('data-remote')) {
  173. this.defer($el, function () {
  174. var data = {}
  175. data[$el.attr('name')] = getValue($el)
  176. $.get($el.attr('data-remote'), data)
  177. .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
  178. .always(function () { deferred.resolve(errors)})
  179. })
  180. } else deferred.resolve(errors)
  181. return deferred.promise()
  182. }
  183. Validator.prototype.validate = function () {
  184. var self = this
  185. $.when(this.$inputs.map(function (el) {
  186. return self.validateInput($(this), false)
  187. })).then(function () {
  188. self.toggleSubmit()
  189. self.focusError()
  190. })
  191. return this
  192. }
  193. Validator.prototype.focusError = function () {
  194. if (!this.options.focus) return
  195. var $input = this.$element.find(".has-error:first :input")
  196. if ($input.length === 0) return
  197. $('html, body').animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250)
  198. $input.focus()
  199. }
  200. Validator.prototype.showErrors = function ($el) {
  201. var method = this.options.html ? 'html' : 'text'
  202. var errors = $el.data('bs.validator.errors')
  203. var $group = $el.closest('.form-group')
  204. var $block = $group.find('.help-block.with-errors')
  205. var $feedback = $group.find('.form-control-feedback')
  206. if (!errors.length) return
  207. errors = $('<ul/>')
  208. .addClass('list-unstyled')
  209. .append($.map(errors, function (error) { return $('<li/>')[method](error) }))
  210. $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
  211. $block.empty().append(errors)
  212. $group.addClass('has-error has-danger')
  213. $group.hasClass('has-feedback')
  214. && $feedback.removeClass(this.options.feedback.success)
  215. && $feedback.addClass(this.options.feedback.error)
  216. && $group.removeClass('has-success')
  217. }
  218. Validator.prototype.clearErrors = function ($el) {
  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. $block.html($block.data('bs.validator.originalContent'))
  223. $group.removeClass('has-error has-danger has-success')
  224. $group.hasClass('has-feedback')
  225. && $feedback.removeClass(this.options.feedback.error)
  226. && $feedback.removeClass(this.options.feedback.success)
  227. && getValue($el)
  228. && $feedback.addClass(this.options.feedback.success)
  229. && $group.addClass('has-success')
  230. }
  231. Validator.prototype.hasErrors = function () {
  232. function fieldErrors() {
  233. return !!($(this).data('bs.validator.errors') || []).length
  234. }
  235. return !!this.$inputs.filter(fieldErrors).length
  236. }
  237. Validator.prototype.isIncomplete = function () {
  238. function fieldIncomplete() {
  239. var value = getValue($(this))
  240. return !(typeof value == "string" ? $.trim(value) : value)
  241. }
  242. return !!this.$inputs.filter('[required]').filter(fieldIncomplete).length
  243. }
  244. Validator.prototype.onSubmit = function (e) {
  245. this.validate()
  246. if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
  247. }
  248. Validator.prototype.toggleSubmit = function () {
  249. if (!this.options.disable) return
  250. this.$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
  251. }
  252. Validator.prototype.defer = function ($el, callback) {
  253. callback = $.proxy(callback, this, $el)
  254. if (!this.options.delay) return callback()
  255. window.clearTimeout($el.data('bs.validator.timeout'))
  256. $el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
  257. }
  258. Validator.prototype.reset = function () {
  259. this.$element.find('.form-control-feedback')
  260. .removeClass(this.options.feedback.error)
  261. .removeClass(this.options.feedback.success)
  262. this.$inputs
  263. .removeData(['bs.validator.errors', 'bs.validator.deferred'])
  264. .each(function () {
  265. var $this = $(this)
  266. var timeout = $this.data('bs.validator.timeout')
  267. window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
  268. })
  269. this.$element.find('.help-block.with-errors')
  270. .each(function () {
  271. var $this = $(this)
  272. var originalContent = $this.data('bs.validator.originalContent')
  273. $this
  274. .removeData('bs.validator.originalContent')
  275. .html(originalContent)
  276. })
  277. this.$btn.removeClass('disabled')
  278. this.$element.find('.has-error, .has-danger, .has-success').removeClass('has-error has-danger has-success')
  279. return this
  280. }
  281. Validator.prototype.destroy = function () {
  282. this.reset()
  283. this.$element
  284. .removeAttr('novalidate')
  285. .removeData('bs.validator')
  286. .off('.bs.validator')
  287. this.$inputs
  288. .off('.bs.validator')
  289. this.options = null
  290. this.validators = null
  291. this.$element = null
  292. this.$btn = null
  293. this.$inputs = null
  294. return this
  295. }
  296. // VALIDATOR PLUGIN DEFINITION
  297. // ===========================
  298. function Plugin(option) {
  299. return this.each(function () {
  300. var $this = $(this)
  301. var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
  302. var data = $this.data('bs.validator')
  303. if (!data && option == 'destroy') return
  304. if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
  305. if (typeof option == 'string') data[option]()
  306. })
  307. }
  308. var old = $.fn.validator
  309. $.fn.validator = Plugin
  310. $.fn.validator.Constructor = Validator
  311. // VALIDATOR NO CONFLICT
  312. // =====================
  313. $.fn.validator.noConflict = function () {
  314. $.fn.validator = old
  315. return this
  316. }
  317. // VALIDATOR DATA-API
  318. // ==================
  319. $(window).on('load', function () {
  320. $('form[data-toggle="validator"]').each(function () {
  321. var $form = $(this)
  322. Plugin.call($form, $form.data())
  323. })
  324. })
  325. }(jQuery);