validator.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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, rule = $el.attr('data-' + key) || null
  146. if (
  147. (getValue($el) || $el.attr('required') || key == 'match') &&
  148. (rule || key == 'native') &&
  149. (error = validator.call(this, $el))
  150. ) {
  151. error = getErrorMessage(key) || error
  152. !~errors.indexOf(error) && errors.push(error)
  153. }
  154. }, this))
  155. if (!errors.length && getValue($el) && $el.attr('data-remote')) {
  156. this.defer($el, function () {
  157. var data = {}
  158. data[$el.attr('name')] = getValue($el)
  159. $.get($el.attr('data-remote'), data)
  160. .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
  161. .always(function () { deferred.resolve(errors)})
  162. })
  163. } else deferred.resolve(errors)
  164. return deferred.promise()
  165. }
  166. Validator.prototype.validate = function () {
  167. var self = this
  168. $.when(this.$inputs.map(function (el) {
  169. return self.validateInput($(this), false)
  170. })).then(function () {
  171. self.toggleSubmit()
  172. self.focusError()
  173. })
  174. return this
  175. }
  176. Validator.prototype.focusError = function () {
  177. if (!this.options.focus) return
  178. var $input = this.$element.find(".has-error:first :input")
  179. if ($input.length === 0) return
  180. $('html, body').animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250)
  181. $input.focus()
  182. }
  183. Validator.prototype.showErrors = function ($el) {
  184. var method = this.options.html ? 'html' : 'text'
  185. var errors = $el.data('bs.validator.errors')
  186. var $group = $el.closest('.form-group')
  187. var $block = $group.find('.help-block.with-errors')
  188. var $feedback = $group.find('.form-control-feedback')
  189. if (!errors.length) return
  190. errors = $('<ul/>')
  191. .addClass('list-unstyled')
  192. .append($.map(errors, function (error) { return $('<li/>')[method](error) }))
  193. $block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
  194. $block.empty().append(errors)
  195. $group.addClass('has-error has-danger')
  196. $group.hasClass('has-feedback')
  197. && $feedback.removeClass(this.options.feedback.success)
  198. && $feedback.addClass(this.options.feedback.error)
  199. && $group.removeClass('has-success')
  200. }
  201. Validator.prototype.clearErrors = function ($el) {
  202. var $group = $el.closest('.form-group')
  203. var $block = $group.find('.help-block.with-errors')
  204. var $feedback = $group.find('.form-control-feedback')
  205. $block.html($block.data('bs.validator.originalContent'))
  206. $group.removeClass('has-error has-danger has-success')
  207. $group.hasClass('has-feedback')
  208. && $feedback.removeClass(this.options.feedback.error)
  209. && $feedback.removeClass(this.options.feedback.success)
  210. && getValue($el)
  211. && $feedback.addClass(this.options.feedback.success)
  212. && $group.addClass('has-success')
  213. }
  214. Validator.prototype.hasErrors = function () {
  215. function fieldErrors() {
  216. return !!($(this).data('bs.validator.errors') || []).length
  217. }
  218. return !!this.$inputs.filter(fieldErrors).length
  219. }
  220. Validator.prototype.isIncomplete = function () {
  221. function fieldIncomplete() {
  222. var value = getValue($(this))
  223. return !(typeof value == "string" ? $.trim(value) : value)
  224. }
  225. return !!this.$inputs.filter('[required]').filter(fieldIncomplete).length
  226. }
  227. Validator.prototype.onSubmit = function (e) {
  228. this.validate()
  229. if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
  230. }
  231. Validator.prototype.toggleSubmit = function () {
  232. if (!this.options.disable) return
  233. this.$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
  234. }
  235. Validator.prototype.defer = function ($el, callback) {
  236. callback = $.proxy(callback, this, $el)
  237. if (!this.options.delay) return callback()
  238. window.clearTimeout($el.data('bs.validator.timeout'))
  239. $el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
  240. }
  241. Validator.prototype.reset = function () {
  242. this.$element.find('.form-control-feedback')
  243. .removeClass(this.options.feedback.error)
  244. .removeClass(this.options.feedback.success)
  245. this.$inputs
  246. .removeData(['bs.validator.errors', 'bs.validator.deferred'])
  247. .each(function () {
  248. var $this = $(this)
  249. var timeout = $this.data('bs.validator.timeout')
  250. window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
  251. })
  252. this.$element.find('.help-block.with-errors')
  253. .each(function () {
  254. var $this = $(this)
  255. var originalContent = $this.data('bs.validator.originalContent')
  256. $this
  257. .removeData('bs.validator.originalContent')
  258. .html(originalContent)
  259. })
  260. this.$btn.removeClass('disabled')
  261. this.$element.find('.has-error, .has-danger, .has-success').removeClass('has-error has-danger has-success')
  262. return this
  263. }
  264. Validator.prototype.destroy = function () {
  265. this.reset()
  266. this.$element
  267. .removeAttr('novalidate')
  268. .removeData('bs.validator')
  269. .off('.bs.validator')
  270. this.$inputs
  271. .off('.bs.validator')
  272. this.options = null
  273. this.validators = null
  274. this.$element = null
  275. this.$btn = null
  276. this.$inputs = null
  277. return this
  278. }
  279. // VALIDATOR PLUGIN DEFINITION
  280. // ===========================
  281. function Plugin(option) {
  282. return this.each(function () {
  283. var $this = $(this)
  284. var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
  285. var data = $this.data('bs.validator')
  286. if (!data && option == 'destroy') return
  287. if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
  288. if (typeof option == 'string') data[option]()
  289. })
  290. }
  291. var old = $.fn.validator
  292. $.fn.validator = Plugin
  293. $.fn.validator.Constructor = Validator
  294. // VALIDATOR NO CONFLICT
  295. // =====================
  296. $.fn.validator.noConflict = function () {
  297. $.fn.validator = old
  298. return this
  299. }
  300. // VALIDATOR DATA-API
  301. // ==================
  302. $(window).on('load', function () {
  303. $('form[data-toggle="validator"]').each(function () {
  304. var $form = $(this)
  305. Plugin.call($form, $form.data())
  306. })
  307. })
  308. }(jQuery);