validator.js 12 KB

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