bootstrapValidator.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. /**
  2. * BootstrapValidator (http://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @version v0.3.1-dev
  7. * @author https://twitter.com/nghuuphuoc
  8. * @copyright (c) 2013 - 2014 Nguyen Huu Phuoc
  9. * @license MIT
  10. */
  11. (function($) {
  12. var BootstrapValidator = function(form, options) {
  13. this.$form = $(form);
  14. this.options = $.extend({}, BootstrapValidator.DEFAULT_OPTIONS, options);
  15. this.dfds = {}; // Array of deferred
  16. this.results = {}; // Validating results
  17. this.invalidField = null; // First invalid field
  18. this.$submitButton = null; // The submit button which is clicked to submit form
  19. this._init();
  20. this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
  21. this.STATUS_VALIDATING = 'VALIDATING';
  22. this.STATUS_INVALID = 'INVALID';
  23. this.STATUS_VALID = 'VALID';
  24. };
  25. // The default options
  26. BootstrapValidator.DEFAULT_OPTIONS = {
  27. // The form CSS class
  28. elementClass: 'bootstrap-validator-form',
  29. // Default invalid message
  30. message: 'This value is not valid',
  31. // The number of grid columns
  32. // Change it if you use custom grid with different number of columns
  33. columns: 12,
  34. // Shows ok/error/loading icons based on the field validity.
  35. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  36. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  37. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  38. //
  39. // Examples:
  40. // - Use Glyphicons icons:
  41. // feedbackIcons: {
  42. // valid: 'glyphicon glyphicon-ok',
  43. // invalid: 'glyphicon glyphicon-remove',
  44. // validating: 'glyphicon glyphicon-refresh'
  45. // }
  46. // - Use FontAwesome icons:
  47. // feedbackIcons: {
  48. // valid: 'fa fa-check',
  49. // invalid: 'fa fa-times',
  50. // validating: 'fa fa-refresh'
  51. // }
  52. feedbackIcons: null,
  53. // The submit buttons selector
  54. // These buttons will be disabled to prevent the valid form from multiple submissions
  55. submitButtons: 'button[type="submit"]',
  56. // The custom submit handler
  57. // It will prevent the form from the default submission
  58. //
  59. // submitHandler: function(validator, form) {
  60. // - validator is the BootstrapValidator instance
  61. // - form is the jQuery object present the current form
  62. // }
  63. submitHandler: null,
  64. // Live validating option
  65. // Can be one of 3 values:
  66. // - enabled: The plugin validates fields as soon as they are changed
  67. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  68. // - submitted: The live validating is enabled after the form is submitted
  69. live: 'enabled',
  70. // Map the field name with validator rules
  71. fields: null
  72. };
  73. BootstrapValidator.prototype = {
  74. constructor: BootstrapValidator,
  75. /**
  76. * Init form
  77. */
  78. _init: function() {
  79. if (this.options.fields == null) {
  80. return;
  81. }
  82. var that = this;
  83. this.$form
  84. // Disable client side validation in HTML 5
  85. .attr('novalidate', 'novalidate')
  86. .addClass(this.options.elementClass)
  87. // Disable the default submission first
  88. .on('submit.bootstrapValidator', function(e) {
  89. e.preventDefault();
  90. that.validate();
  91. })
  92. .find(this.options.submitButtons)
  93. .on('click', function() {
  94. that.$submitButton = $(this);
  95. });
  96. for (var field in this.options.fields) {
  97. this._initField(field);
  98. }
  99. this._setLiveValidating();
  100. },
  101. /**
  102. * Init field
  103. *
  104. * @param {String} field The field name
  105. */
  106. _initField: function(field) {
  107. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  108. return;
  109. }
  110. this.dfds[field] = {};
  111. this.results[field] = {};
  112. var fields = this.getFieldElements(field);
  113. // We don't need to validate non-existing fields
  114. if (fields == null) {
  115. delete this.options.fields[field];
  116. delete this.dfds[field];
  117. return;
  118. }
  119. // Create a help block element for showing the error
  120. var $field = $(fields[0]),
  121. $parent = $field.parents('.form-group'),
  122. // Calculate the number of columns of the label/field element
  123. // Then set offset to the help block element
  124. label, cssClasses, offset, size;
  125. if (label = $parent.find('label').get(0)) {
  126. // The default Bootstrap form don't require class for label (http://getbootstrap.com/css/#forms)
  127. if (cssClasses = $(label).attr('class')) {
  128. cssClasses = cssClasses.split(' ');
  129. for (var i = 0; i < cssClasses.length; i++) {
  130. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i])) {
  131. offset = cssClasses[i].substr(7);
  132. size = cssClasses[i].substr(4, 2);
  133. break;
  134. }
  135. }
  136. }
  137. } else if (cssClasses = $parent.children().eq(0).attr('class')) {
  138. cssClasses = cssClasses.split(' ');
  139. for (var i = 0; i < cssClasses.length; i++) {
  140. if (/^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  141. offset = cssClasses[i].substr(14);
  142. size = cssClasses[i].substr(4, 2);
  143. break;
  144. }
  145. }
  146. }
  147. for (var validatorName in this.options.fields[field].validators) {
  148. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  149. delete this.options.fields[field].validators[validatorName];
  150. continue;
  151. }
  152. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  153. $('<small/>')
  154. .css('display', 'none')
  155. .attr('data-bs-validator', validatorName)
  156. .addClass('help-block')
  157. .addClass(size && offset ? ['col-', size, '-offset-', offset].join('') : '')
  158. .addClass(size && offset ? ['col-', size, '-', this.options.columns - offset].join('') : '')
  159. .appendTo($parent);
  160. }
  161. // Prepare the feedback icons
  162. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  163. if (this.options.feedbackIcons) {
  164. $parent.addClass('has-feedback');
  165. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').insertAfter($(fields[fields.length - 1]));
  166. // The feedback icon does not render correctly if there is no label
  167. // https://github.com/twbs/bootstrap/issues/12873
  168. if (label == null) {
  169. $icon.css('top', 0);
  170. }
  171. }
  172. if (this.options.fields[field]['enabled'] == null) {
  173. this.options.fields[field]['enabled'] = true;
  174. }
  175. // Whenever the user change the field value, mark it as not validated yet
  176. var that = this,
  177. type = fields.attr('type'),
  178. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  179. fields.on(event, function() {
  180. for (var v in that.options.fields[field].validators) {
  181. that.results[field][v] = that.STATUS_NOT_VALIDATED;
  182. }
  183. });
  184. },
  185. /**
  186. * Enable live validating
  187. */
  188. _setLiveValidating: function() {
  189. if ('enabled' == this.options.live) {
  190. var that = this;
  191. for (var field in this.options.fields) {
  192. (function(f) {
  193. var fields = that.getFieldElements(f);
  194. if (fields) {
  195. var type = fields.attr('type'),
  196. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  197. fields.on(event, function() {
  198. that.validateField(f);
  199. });
  200. }
  201. })(field);
  202. }
  203. }
  204. },
  205. /**
  206. * Disable/Enable submit buttons
  207. *
  208. * @param {Boolean} disabled
  209. */
  210. _disableSubmitButtons: function(disabled) {
  211. if (!disabled) {
  212. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  213. } else if (this.options.live != 'disabled') {
  214. // Don't disable if the live validating mode is disabled
  215. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  216. }
  217. },
  218. /**
  219. * Called when all validations are completed
  220. */
  221. _submit: function() {
  222. if (!this.isValid()) {
  223. if ('submitted' == this.options.live) {
  224. this.options.live = 'enabled';
  225. this._setLiveValidating();
  226. }
  227. // Focus to the first invalid field
  228. if (this.invalidField) {
  229. this.getFieldElements(this.invalidField).focus();
  230. }
  231. return;
  232. }
  233. this._disableSubmitButtons(true);
  234. // Call the custom submission if enabled
  235. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  236. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  237. } else {
  238. // Submit form
  239. this.$form.off('submit.bootstrapValidator').submit();
  240. }
  241. },
  242. // --- Public methods ---
  243. /**
  244. * Retrieve the field elements by given name
  245. *
  246. * @param {String} field The field name
  247. * @returns {null|jQuery[]}
  248. */
  249. getFieldElements: function(field) {
  250. var fields = this.$form.find('[name="' + field + '"]');
  251. return (fields.length == 0) ? null : fields;
  252. },
  253. /**
  254. * Validate the form
  255. *
  256. * @return {BootstrapValidator}
  257. */
  258. validate: function() {
  259. if (!this.options.fields) {
  260. return this;
  261. }
  262. this._disableSubmitButtons(true);
  263. for (var field in this.options.fields) {
  264. this.validateField(field);
  265. }
  266. this._submit();
  267. return this;
  268. },
  269. /**
  270. * Validate given field
  271. *
  272. * @param {String} field The field name
  273. */
  274. validateField: function(field) {
  275. if (!this.options.fields[field]['enabled']) {
  276. return;
  277. }
  278. var that = this,
  279. fields = this.getFieldElements(field),
  280. $field = $(fields[0]),
  281. validators = this.options.fields[field].validators,
  282. validatorName,
  283. validateResult;
  284. // We don't need to validate disabled field
  285. if (fields.length == 1 && fields.is(':disabled')) {
  286. delete this.options.fields[field];
  287. delete this.dfds[field];
  288. return;
  289. }
  290. for (validatorName in validators) {
  291. if (this.dfds[field][validatorName]) {
  292. this.dfds[field][validatorName].reject();
  293. }
  294. // Don't validate field if it is already done
  295. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  296. continue;
  297. }
  298. this.results[field][validatorName] = this.STATUS_VALIDATING;
  299. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  300. if ('object' == typeof validateResult) {
  301. this.updateStatus($field, validatorName, this.STATUS_VALIDATING);
  302. this.dfds[field][validatorName] = validateResult;
  303. validateResult.done(function(isValid, v) {
  304. // v is validator name
  305. delete that.dfds[field][v];
  306. isValid ? that.updateStatus($field, v, that.STATUS_VALID)
  307. : that.updateStatus($field, v, that.STATUS_INVALID);
  308. });
  309. } else if ('boolean' == typeof validateResult) {
  310. validateResult ? this.updateStatus($field, validatorName, this.STATUS_VALID)
  311. : this.updateStatus($field, validatorName, this.STATUS_INVALID);
  312. }
  313. }
  314. },
  315. /**
  316. * Check the form validity
  317. *
  318. * @returns {Boolean}
  319. */
  320. isValid: function() {
  321. var field, validatorName;
  322. for (field in this.results) {
  323. if (!this.options.fields[field]['enabled']) {
  324. continue;
  325. }
  326. for (validatorName in this.results[field]) {
  327. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  328. return false;
  329. }
  330. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  331. this.invalidField = field;
  332. return false;
  333. }
  334. }
  335. }
  336. return true;
  337. },
  338. /**
  339. * Update field status
  340. *
  341. * @param {jQuery} $field The field element
  342. * @param {String} validatorName
  343. * @param {String} status The status
  344. * Can be STATUS_VALIDATING, STATUS_INVALID, STATUS_VALID
  345. * @return {BootstrapValidator}
  346. */
  347. updateStatus: function($field, validatorName, status) {
  348. var that = this,
  349. field = $field.attr('name'),
  350. validator = this.options.fields[field].validators[validatorName],
  351. message = validator.message || this.options.message,
  352. $parent = $field.parents('.form-group'),
  353. $errors = $parent.find('.help-block[data-bs-validator]');
  354. switch (status) {
  355. case this.STATUS_VALIDATING:
  356. this.results[field][validatorName] = this.STATUS_VALIDATING;
  357. this._disableSubmitButtons(true);
  358. $parent.removeClass('has-success').removeClass('has-error');
  359. // TODO: Show validating message
  360. $errors.filter('.help-block[data-bs-validator="' + validatorName + '"]').html(message).hide();
  361. if (this.options.feedbackIcons) {
  362. // Show validating icon
  363. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  364. }
  365. break;
  366. case this.STATUS_INVALID:
  367. this.results[field][validatorName] = this.STATUS_INVALID;
  368. this._disableSubmitButtons(true);
  369. // Add has-error class to parent element
  370. $parent.removeClass('has-success').addClass('has-error');
  371. $errors.filter('[data-bs-validator="' + validatorName + '"]').html(message).show();
  372. if (this.options.feedbackIcons) {
  373. // Show invalid icon
  374. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  375. }
  376. break;
  377. case this.STATUS_VALID:
  378. this.results[field][validatorName] = this.STATUS_VALID;
  379. // Hide error element
  380. $errors.filter('[data-bs-validator="' + validatorName + '"]').hide();
  381. // If the field is valid
  382. if ($errors.filter(function() {
  383. var display = $(this).css('display'), v = $(this).attr('data-bs-validator');
  384. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  385. }).length == 0
  386. ) {
  387. this._disableSubmitButtons(false);
  388. $parent.removeClass('has-error').addClass('has-success');
  389. // Show valid icon
  390. if (this.options.feedbackIcons) {
  391. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  392. }
  393. }
  394. break;
  395. default:
  396. break;
  397. }
  398. return this;
  399. },
  400. // Useful APIs which aren't used internally
  401. /**
  402. * Reset the form
  403. *
  404. * @param {Boolean} resetFormData Reset current form data
  405. * @return {BootstrapValidator}
  406. */
  407. resetForm: function(resetFormData) {
  408. for (var field in this.options.fields) {
  409. this.dfds[field] = {};
  410. this.results[field] = {};
  411. // Mark all fields as not validated yet
  412. for (var v in this.options.fields[field].validators) {
  413. this.results[field][v] = this.STATUS_NOT_VALIDATED;
  414. }
  415. }
  416. this.invalidField = null;
  417. this.$submitButton = null;
  418. // Hide all error elements
  419. this.$form
  420. .find('.has-error').removeClass('has-error').end()
  421. .find('.has-success').removeClass('has-success').end()
  422. .find('.help-block[data-bs-validator]').hide();
  423. // Enable submit buttons
  424. this._disableSubmitButtons(false);
  425. // Hide all feedback icons
  426. if (this.options.feedbackIcons) {
  427. this.$form.find('.form-control-feedback').removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  428. }
  429. if (resetFormData) {
  430. this.$form.get(0).reset();
  431. }
  432. return this;
  433. },
  434. /**
  435. * Enable/Disable all validators to given field
  436. *
  437. * @param {String} field The field name
  438. * @param {Boolean} enabled Enable/Disable field validators
  439. * @return {BootstrapValidator}
  440. */
  441. enableFieldValidators: function(field, enabled) {
  442. this.options.fields[field]['enabled'] = enabled;
  443. if (enabled) {
  444. for (var v in this.options.fields[field].validators) {
  445. this.results[field][v] = this.STATUS_NOT_VALIDATED;
  446. }
  447. } else {
  448. var $field = this.getFieldElements(field),
  449. $parent = $field.parents('.form-group');
  450. $parent.removeClass('has-success has-error').find('.help-block[data-bs-validator]').hide();
  451. if (this.options.feedbackIcons) {
  452. $parent.find('.form-control-feedback').removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).removeClass(this.options.feedbackIcons.valid).hide();
  453. }
  454. this._disableSubmitButtons(false);
  455. }
  456. return this;
  457. }
  458. };
  459. // Plugin definition
  460. $.fn.bootstrapValidator = function(options) {
  461. return this.each(function() {
  462. var $this = $(this), data = $this.data('bootstrapValidator');
  463. if (!data) {
  464. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  465. }
  466. if ('string' == typeof options) {
  467. data[options]();
  468. }
  469. });
  470. };
  471. // Available validators
  472. $.fn.bootstrapValidator.validators = {};
  473. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  474. }(window.jQuery));
  475. ;(function($) {
  476. $.fn.bootstrapValidator.validators.between = {
  477. /**
  478. * Return true if the input value is between (strictly or not) two given numbers
  479. *
  480. * @param {BootstrapValidator} validator The validator plugin instance
  481. * @param {jQuery} $field Field element
  482. * @param {Object} options Can consist of the following keys:
  483. * - min
  484. * - max
  485. * - inclusive [optional]: Can be true or false. Default is true
  486. * - message: The invalid message
  487. * @returns {Boolean}
  488. */
  489. validate: function(validator, $field, options) {
  490. var value = $field.val();
  491. if (value == '') {
  492. return true;
  493. }
  494. value = parseFloat(value);
  495. return (options.inclusive === true)
  496. ? (value > options.min && value < options.max)
  497. : (value >= options.min && value <= options.max);
  498. }
  499. };
  500. }(window.jQuery));
  501. ;(function($) {
  502. $.fn.bootstrapValidator.validators.callback = {
  503. /**
  504. * Return result from the callback method
  505. *
  506. * @param {BootstrapValidator} validator The validator plugin instance
  507. * @param {jQuery} $field Field element
  508. * @param {Object} options Can consist of the following keys:
  509. * - callback: The callback method that passes 2 parameters:
  510. * callback: function(fieldValue, validator) {
  511. * // fieldValue is the value of field
  512. * // validator is instance of BootstrapValidator
  513. * }
  514. * - message: The invalid message
  515. * @returns {Boolean|Deferred}
  516. */
  517. validate: function(validator, $field, options) {
  518. var value = $field.val();
  519. if (options.callback && 'function' == typeof options.callback) {
  520. var dfd = new $.Deferred();
  521. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  522. return dfd;
  523. return options.callback.call(this, value, validator);
  524. }
  525. return true;
  526. }
  527. };
  528. }(window.jQuery));
  529. ;(function($) {
  530. $.fn.bootstrapValidator.validators.choice = {
  531. /**
  532. * Check if the number of checked boxes are less or more than a given number
  533. *
  534. * @param {BootstrapValidator} validator The validator plugin instance
  535. * @param {jQuery} $field Field element
  536. * @param {Object} options Consists of following keys:
  537. * - min
  538. * - max
  539. * At least one of two keys is required
  540. * @returns {Boolean}
  541. */
  542. validate: function(validator, $field, options) {
  543. var numChoices = validator
  544. .getFieldElements($field.attr('name'))
  545. .filter(':checked')
  546. .length;
  547. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  548. return false;
  549. }
  550. return true;
  551. }
  552. };
  553. }(window.jQuery));
  554. ;(function($) {
  555. $.fn.bootstrapValidator.validators.creditCard = {
  556. /**
  557. * Return true if the input value is valid credit card number
  558. * Based on https://gist.github.com/DiegoSalazar/4075533
  559. *
  560. * @param {BootstrapValidator} validator The validator plugin instance
  561. * @param {jQuery} $field Field element
  562. * @param {Object} options Can consist of the following key:
  563. * - message: The invalid message
  564. * @returns {Boolean}
  565. */
  566. validate: function(validator, $field, options) {
  567. var value = $field.val();
  568. if (value == '') {
  569. return true;
  570. }
  571. // Accept only digits, dashes or spaces
  572. if (/[^0-9-\s]+/.test(value)) {
  573. return false;
  574. }
  575. // The Luhn Algorithm
  576. // http://en.wikipedia.org/wiki/Luhn
  577. value = value.replace(/\D/g, '');
  578. var check = 0, digit = 0, even = false, length = value.length;
  579. for (var n = length - 1; n >= 0; n--) {
  580. digit = parseInt(value.charAt(n), 10);
  581. if (even) {
  582. if ((digit *= 2) > 9) {
  583. digit -= 9;
  584. }
  585. }
  586. check += digit;
  587. even = !even;
  588. }
  589. return (check % 10) == 0;
  590. }
  591. };
  592. }(window.jQuery));
  593. ;(function($) {
  594. $.fn.bootstrapValidator.validators.date = {
  595. /**
  596. * Return true if the input value is valid date
  597. *
  598. * @param {BootstrapValidator} validator The validator plugin instance
  599. * @param {jQuery} $field Field element
  600. * @param {Object} options Can consist of the following keys:
  601. * - format: The date format. Default is MM/DD/YYYY
  602. * Support the following formats:
  603. * YYYY/DD/MM
  604. * YYYY/DD/MM h:m A
  605. * YYYY/MM/DD
  606. * YYYY/MM/DD h:m A
  607. *
  608. * YYYY-DD-MM
  609. * YYYY-DD-MM h:m A
  610. * YYYY-MM-DD
  611. * YYYY-MM-DD h:m A
  612. *
  613. * MM/DD/YYYY
  614. * MM/DD/YYYY h:m A
  615. * DD/MM/YYYY
  616. * DD/MM/YYYY h:m A
  617. *
  618. * MM-DD-YYYY
  619. * MM-DD-YYYY h:m A
  620. * DD-MM-YYYY
  621. * DD-MM-YYYY h:m A
  622. * - message: The invalid message
  623. * @returns {Boolean}
  624. */
  625. validate: function(validator, $field, options) {
  626. var value = $field.val();
  627. if (value == '') {
  628. return true;
  629. }
  630. // Determine the separator
  631. options.format = options.format || 'MM/DD/YYYY';
  632. var separator = (options.format.indexOf('/') != -1)
  633. ? '/'
  634. : ((options.format.indexOf('-') != -1) ? '-' : null);
  635. if (separator == null) {
  636. return false;
  637. }
  638. var month, day, year, minutes = null, hours = null, matches;
  639. switch (true) {
  640. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/DD/MM'):
  641. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-DD-MM'):
  642. year = matches[1]; day = matches[2]; month = matches[3];
  643. break;
  644. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'DD/MM/YYYY'):
  645. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'DD-MM-YYYY'):
  646. day = matches[1]; month = matches[2]; year = matches[3];
  647. break;
  648. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/MM/DD'):
  649. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-MM-DD'):
  650. year = matches[1]; month = matches[2]; day = matches[3];
  651. break;
  652. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'MM/DD/YYYY'):
  653. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'MM-DD-YYYY'):
  654. month = matches[1]; day = matches[2]; year = matches[3];
  655. break;
  656. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY/DD/MM h:m A'):
  657. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY-DD-MM h:m A'):
  658. year = matches[1]; day = matches[2]; month = matches[3]; hours = matches[4]; minutes = matches[5];
  659. break;
  660. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'DD/MM/YYYY h:m A'):
  661. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'DD-MM-YYYY h:m A'):
  662. day = matches[1]; month = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  663. break;
  664. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY/MM/DD h:m A'):
  665. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'YYYY-MM-DD h:m A'):
  666. year = matches[1]; month = matches[2]; day = matches[3]; hours = matches[4]; minutes = matches[5];
  667. break;
  668. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'MM/DD/YYYY h:m A'):
  669. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})\s+(\d{1,2}):(\d{1,2})\s+(AM|PM)$/i)) && options.format == 'MM-DD-YYYY h:m A'):
  670. month = matches[1]; day = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  671. break;
  672. default:
  673. return false;
  674. }
  675. // Validate hours and minutes
  676. if (hours && minutes) {
  677. hours = parseInt(hours, 10);
  678. minutes = parseInt(minutes, 10);
  679. if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
  680. return false;
  681. }
  682. }
  683. // Validate day, month, and year
  684. day = parseInt(day, 10);
  685. month = parseInt(month, 10);
  686. year = parseInt(year, 10);
  687. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  688. return false;
  689. }
  690. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  691. // Update the number of days in Feb of leap year
  692. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  693. numDays[1] = 29;
  694. }
  695. // Check the day
  696. return (day > 0 && day <= numDays[month - 1]);
  697. }
  698. };
  699. }(window.jQuery));
  700. ;(function($) {
  701. $.fn.bootstrapValidator.validators.different = {
  702. /**
  703. * Return true if the input value is different with given field's value
  704. *
  705. * @param {BootstrapValidator} validator The validator plugin instance
  706. * @param {jQuery} $field Field element
  707. * @param {Object} options Consists of the following key:
  708. * - field: The name of field that will be used to compare with current one
  709. * @returns {Boolean}
  710. */
  711. validate: function(validator, $field, options) {
  712. var value = $field.val();
  713. if (value == '') {
  714. return true;
  715. }
  716. var compareWith = validator.getFieldElements(options.field);
  717. if (compareWith == null) {
  718. return true;
  719. }
  720. if (value != compareWith.val()) {
  721. validator.updateStatus(compareWith, 'different', validator.STATUS_VALID);
  722. return true;
  723. } else {
  724. return false;
  725. }
  726. }
  727. };
  728. }(window.jQuery));
  729. ;(function($) {
  730. $.fn.bootstrapValidator.validators.digits = {
  731. /**
  732. * Return true if the input value contains digits only
  733. *
  734. * @param {BootstrapValidator} validator Validate plugin instance
  735. * @param {jQuery} $field Field element
  736. * @param {Object} options
  737. * @returns {Boolean}
  738. */
  739. validate: function(validator, $field, options) {
  740. var value = $field.val();
  741. if (value == '') {
  742. return true;
  743. }
  744. return /^\d+$/.test(value);
  745. }
  746. }
  747. }(window.jQuery));
  748. ;(function($) {
  749. $.fn.bootstrapValidator.validators.emailAddress = {
  750. /**
  751. * Return true if and only if the input value is a valid email address
  752. *
  753. * @param {BootstrapValidator} validator Validate plugin instance
  754. * @param {jQuery} $field Field element
  755. * @param {Object} options
  756. * @returns {Boolean}
  757. */
  758. validate: function(validator, $field, options) {
  759. var value = $field.val();
  760. if (value == '') {
  761. return true;
  762. }
  763. // Email address regular expression
  764. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  765. var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  766. return emailRegExp.test(value);
  767. }
  768. }
  769. }(window.jQuery));
  770. ;(function($) {
  771. $.fn.bootstrapValidator.validators.greaterThan = {
  772. /**
  773. * Return true if the input value is greater than or equals to given number
  774. *
  775. * @param {BootstrapValidator} validator Validate plugin instance
  776. * @param {jQuery} $field Field element
  777. * @param {Object} options Can consist of the following keys:
  778. * - value: The number used to compare to
  779. * - inclusive [optional]: Can be true or false. Default is true
  780. * - message: The invalid message
  781. * @returns {Boolean}
  782. */
  783. validate: function(validator, $field, options) {
  784. var value = $field.val();
  785. if (value == '') {
  786. return true;
  787. }
  788. value = parseFloat(value);
  789. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  790. }
  791. }
  792. }(window.jQuery));
  793. ;(function($) {
  794. $.fn.bootstrapValidator.validators.hexColor = {
  795. /**
  796. * Return true if the input value is a valid hex color
  797. *
  798. * @param {BootstrapValidator} validator The validator plugin instance
  799. * @param {jQuery} $field Field element
  800. * @param {Object} options Can consist of the following keys:
  801. * - message: The invalid message
  802. * @returns {Boolean}
  803. */
  804. validate: function(validator, $field, options) {
  805. var value = $field.val();
  806. if (value == '') {
  807. return true;
  808. }
  809. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  810. }
  811. };
  812. }(window.jQuery));
  813. ;(function($) {
  814. $.fn.bootstrapValidator.validators.identical = {
  815. /**
  816. * Check if input value equals to value of particular one
  817. *
  818. * @param {BootstrapValidator} validator The validator plugin instance
  819. * @param {jQuery} $field Field element
  820. * @param {Object} options Consists of the following key:
  821. * - field: The name of field that will be used to compare with current one
  822. * @returns {Boolean}
  823. */
  824. validate: function(validator, $field, options) {
  825. var value = $field.val();
  826. if (value == '') {
  827. return true;
  828. }
  829. var compareWith = validator.getFieldElements(options.field);
  830. if (compareWith == null) {
  831. return true;
  832. }
  833. if (value == compareWith.val()) {
  834. validator.updateStatus(compareWith, 'identical', validator.STATUS_VALID);
  835. return true;
  836. } else {
  837. return false;
  838. }
  839. }
  840. };
  841. }(window.jQuery));
  842. ;(function($) {
  843. $.fn.bootstrapValidator.validators.lessThan = {
  844. /**
  845. * Return true if the input value is less than or equal to given number
  846. *
  847. * @param {BootstrapValidator} validator The validator plugin instance
  848. * @param {jQuery} $field Field element
  849. * @param {Object} options Can consist of the following keys:
  850. * - value: The number used to compare to
  851. * - inclusive [optional]: Can be true or false. Default is true
  852. * - message: The invalid message
  853. * @returns {Boolean}
  854. */
  855. validate: function(validator, $field, options) {
  856. var value = $field.val();
  857. if (value == '') {
  858. return true;
  859. }
  860. value = parseFloat(value);
  861. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  862. }
  863. };
  864. }(window.jQuery));
  865. ;(function($) {
  866. $.fn.bootstrapValidator.validators.notEmpty = {
  867. /**
  868. * Check if input value is empty or not
  869. *
  870. * @param {BootstrapValidator} validator The validator plugin instance
  871. * @param {jQuery} $field Field element
  872. * @param {Object} options
  873. * @returns {Boolean}
  874. */
  875. validate: function(validator, $field, options) {
  876. var type = $field.attr('type');
  877. if ('radio' == type || 'checkbox' == type) {
  878. return validator
  879. .getFieldElements($field.attr('name'))
  880. .filter(':checked')
  881. .length > 0;
  882. }
  883. return $.trim($field.val()) != '';
  884. }
  885. };
  886. }(window.jQuery));
  887. ;(function($) {
  888. $.fn.bootstrapValidator.validators.regexp = {
  889. /**
  890. * Check if the element value matches given regular expression
  891. *
  892. * @param {BootstrapValidator} validator The validator plugin instance
  893. * @param {jQuery} $field Field element
  894. * @param {Object} options Consists of the following key:
  895. * - regexp: The regular expression you need to check
  896. * @returns {Boolean}
  897. */
  898. validate: function(validator, $field, options) {
  899. var value = $field.val();
  900. if (value == '') {
  901. return true;
  902. }
  903. return options.regexp.test(value);
  904. }
  905. };
  906. }(window.jQuery));
  907. ;(function($) {
  908. $.fn.bootstrapValidator.validators.remote = {
  909. /**
  910. * Request a remote server to check the input value
  911. *
  912. * @param {BootstrapValidator} validator Plugin instance
  913. * @param {jQuery} $field Field element
  914. * @param {Object} options Can consist of the following keys:
  915. * - url
  916. * - data [optional]: By default, it will take the value
  917. * {
  918. * <fieldName>: <fieldValue>
  919. * }
  920. * - message: The invalid message
  921. * @returns {Boolean|Deferred}
  922. */
  923. validate: function(validator, $field, options) {
  924. var value = $field.val();
  925. if (value == '') {
  926. return true;
  927. }
  928. var name = $field.attr('name'), data = options.data;
  929. if (data == null) {
  930. data = {};
  931. }
  932. // Support dynamic data
  933. if ('function' == typeof data) {
  934. data = data.call(this, validator);
  935. }
  936. data[name] = value;
  937. var dfd = new $.Deferred();
  938. var xhr = $.ajax({
  939. type: 'POST',
  940. url: options.url,
  941. dataType: 'json',
  942. data: data
  943. });
  944. xhr.then(function(response) {
  945. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  946. });
  947. dfd.fail(function() {
  948. xhr.abort();
  949. });
  950. return dfd;
  951. }
  952. };
  953. }(window.jQuery));
  954. ;(function($) {
  955. $.fn.bootstrapValidator.validators.stringLength = {
  956. /**
  957. * Check if the length of element value is less or more than given number
  958. *
  959. * @param {BootstrapValidator} validator The validator plugin instance
  960. * @param {jQuery} $field Field element
  961. * @param {Object} options Consists of following keys:
  962. * - min
  963. * - max
  964. * At least one of two keys is required
  965. * @returns {Boolean}
  966. */
  967. validate: function(validator, $field, options) {
  968. var value = $field.val();
  969. if (value == '') {
  970. return true;
  971. }
  972. var length = $.trim(value).length;
  973. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  974. return false;
  975. }
  976. return true;
  977. }
  978. };
  979. }(window.jQuery));
  980. ;(function($) {
  981. $.fn.bootstrapValidator.validators.uri = {
  982. /**
  983. * Return true if the input value is a valid URL
  984. *
  985. * @param {BootstrapValidator} validator The validator plugin instance
  986. * @param {jQuery} $field Field element
  987. * @param {Object} options
  988. * @returns {Boolean}
  989. */
  990. validate: function(validator, $field, options) {
  991. var value = $field.val();
  992. if (value == '') {
  993. return true;
  994. }
  995. // Credit to https://gist.github.com/dperini/729294
  996. //
  997. // Regular Expression for URL validation
  998. //
  999. // Author: Diego Perini
  1000. // Updated: 2010/12/05
  1001. //
  1002. // the regular expression composed & commented
  1003. // could be easily tweaked for RFC compliance,
  1004. // it was expressly modified to fit & satisfy
  1005. // these test for an URL shortener:
  1006. //
  1007. // http://mathiasbynens.be/demo/url-regex
  1008. //
  1009. // Notes on possible differences from a standard/generic validation:
  1010. //
  1011. // - utf-8 char class take in consideration the full Unicode range
  1012. // - TLDs have been made mandatory so single names like "localhost" fails
  1013. // - protocols have been restricted to ftp, http and https only as requested
  1014. //
  1015. // Changes:
  1016. //
  1017. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  1018. // first and last IP address of each class is considered invalid
  1019. // (since they are broadcast/network addresses)
  1020. //
  1021. // - Added exclusion of private, reserved and/or local networks ranges
  1022. //
  1023. // Compressed one-line versions:
  1024. //
  1025. // Javascript version
  1026. //
  1027. // /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i
  1028. //
  1029. // PHP version
  1030. //
  1031. // _^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
  1032. var urlExp = new RegExp(
  1033. "^" +
  1034. // protocol identifier
  1035. "(?:(?:https?|ftp)://)" +
  1036. // user:pass authentication
  1037. "(?:\\S+(?::\\S*)?@)?" +
  1038. "(?:" +
  1039. // IP address exclusion
  1040. // private & local networks
  1041. "(?!10(?:\\.\\d{1,3}){3})" +
  1042. "(?!127(?:\\.\\d{1,3}){3})" +
  1043. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  1044. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  1045. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  1046. // IP address dotted notation octets
  1047. // excludes loopback network 0.0.0.0
  1048. // excludes reserved space >= 224.0.0.0
  1049. // excludes network & broacast addresses
  1050. // (first & last IP address of each class)
  1051. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1052. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1053. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1054. "|" +
  1055. // host name
  1056. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  1057. // domain name
  1058. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1059. // TLD identifier
  1060. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1061. ")" +
  1062. // port number
  1063. "(?::\\d{2,5})?" +
  1064. // resource path
  1065. "(?:/[^\\s]*)?" +
  1066. "$", "i"
  1067. );
  1068. return urlExp.test(value);
  1069. }
  1070. };
  1071. }(window.jQuery));
  1072. ;(function($) {
  1073. $.fn.bootstrapValidator.validators.zipCode = {
  1074. /**
  1075. * Return true if and only if the input value is a valid country zip code
  1076. *
  1077. * @param {BootstrapValidator} validator The validator plugin instance
  1078. * @param {jQuery} $field Field element
  1079. * @param {Object} options Consist of key:
  1080. * - country: The ISO 3166 country code
  1081. *
  1082. * Currently it supports the following countries:
  1083. * - US (United State)
  1084. * - DK (Denmark)
  1085. * - SE (Sweden)
  1086. *
  1087. * @returns {Boolean}
  1088. */
  1089. validate: function(validateInstance, $field, options) {
  1090. var value = $field.val();
  1091. if (value == '' || !options.country) {
  1092. return true;
  1093. }
  1094. switch (options.country.toUpperCase()) {
  1095. case 'DK':
  1096. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  1097. case 'SE':
  1098. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  1099. case 'US':
  1100. default:
  1101. return /^\d{5}([\-]\d{4})?$/.test(value);
  1102. }
  1103. }
  1104. };
  1105. }(window.jQuery));