bootstrapValidator.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. /**
  2. * BootstrapValidator (https://github.com/nghuuphuoc/bootstrapvalidator)
  3. *
  4. * A jQuery plugin to validate form fields. Use with Bootstrap 3
  5. *
  6. * @version v0.4.0-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. // Shows ok/error/loading icons based on the field validity.
  32. // This feature requires Bootstrap v3.1.0 or later (http://getbootstrap.com/css/#forms-control-validation).
  33. // Since Bootstrap doesn't provide any methods to know its version, this option cannot be on/off automatically.
  34. // In other word, to use this feature you have to upgrade your Bootstrap to v3.1.0 or later.
  35. //
  36. // Examples:
  37. // - Use Glyphicons icons:
  38. // feedbackIcons: {
  39. // valid: 'glyphicon glyphicon-ok',
  40. // invalid: 'glyphicon glyphicon-remove',
  41. // validating: 'glyphicon glyphicon-refresh'
  42. // }
  43. // - Use FontAwesome icons:
  44. // feedbackIcons: {
  45. // valid: 'fa fa-check',
  46. // invalid: 'fa fa-times',
  47. // validating: 'fa fa-refresh'
  48. // }
  49. feedbackIcons: {
  50. valid: null,
  51. invalid: null,
  52. validating: null
  53. },
  54. // The submit buttons selector
  55. // These buttons will be disabled to prevent the valid form from multiple submissions
  56. submitButtons: 'button[type="submit"]',
  57. // The custom submit handler
  58. // It will prevent the form from the default submission
  59. //
  60. // submitHandler: function(validator, form) {
  61. // - validator is the BootstrapValidator instance
  62. // - form is the jQuery object present the current form
  63. // }
  64. submitHandler: null,
  65. // Live validating option
  66. // Can be one of 3 values:
  67. // - enabled: The plugin validates fields as soon as they are changed
  68. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  69. // - submitted: The live validating is enabled after the form is submitted
  70. live: 'enabled',
  71. // Map the field name with validator rules
  72. fields: null
  73. };
  74. BootstrapValidator.prototype = {
  75. constructor: BootstrapValidator,
  76. /**
  77. * Init form
  78. */
  79. _init: function() {
  80. var that = this,
  81. options = {
  82. message: this.$form.attr('data-bv-message'),
  83. submitButtons: this.$form.attr('data-bv-submitbuttons'),
  84. live: this.$form.attr('data-bv-live'),
  85. fields: {},
  86. feedbackIcons: {
  87. valid: this.$form.attr('data-bv-feedbackicons-valid'),
  88. invalid: this.$form.attr('data-bv-feedbackicons-invalid'),
  89. validating: this.$form.attr('data-bv-feedbackicons-validating')
  90. }
  91. },
  92. validator,
  93. i = 0,
  94. v, // Validator name
  95. enabled,
  96. optionName,
  97. optionValue,
  98. html5Attrs;
  99. this.$form
  100. // Disable client side validation in HTML 5
  101. .attr('novalidate', 'novalidate')
  102. .addClass(this.options.elementClass)
  103. // Disable the default submission first
  104. .on('submit.bootstrapValidator', function(e) {
  105. e.preventDefault();
  106. that.validate();
  107. })
  108. .on('click', this.options.submitButtons, function() {
  109. that.$submitButton = $(this);
  110. })
  111. // Find all fields which have either "name" or "data-bv-field" attribute
  112. .find('[name], [data-bv-field]').each(function() {
  113. var $field = $(this),
  114. field = $field.attr('name') || $field.attr('data-bv-field');
  115. $field.attr('data-bv-field', field);
  116. options.fields[field] = $.extend({}, {
  117. message: $field.attr('data-bv-message'),
  118. container: $field.attr('data-bv-container'),
  119. selector: $field.attr('data-bv-selector'),
  120. validators: {}
  121. }, options.fields[field]);
  122. for (v in $.fn.bootstrapValidator.validators) {
  123. validator = $.fn.bootstrapValidator.validators[v];
  124. enabled = $field.attr('data-bv-' + v.toLowerCase()) + '';
  125. html5Attrs = {};
  126. if (('function' == typeof validator.enableByHtml5
  127. && (html5Attrs = validator.enableByHtml5($(this)))
  128. && (enabled != 'false'))
  129. || ('undefined' == typeof validator.enableByHtml5 && ('' == enabled || 'true' == enabled)))
  130. {
  131. // Try to parse the options via attributes
  132. validator.html5Attributes = validator.html5Attributes || ['message'];
  133. options.fields[field]['validators'][v] = $.extend({}, html5Attrs == true ? {} : html5Attrs, options.fields[field]['validators'][v]);
  134. for (i in validator.html5Attributes) {
  135. optionName = validator.html5Attributes[i];
  136. optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + optionName.toLowerCase());
  137. if (optionValue) {
  138. if ('true' == optionValue) {
  139. optionValue = true;
  140. } else if ('false' == optionValue) {
  141. optionValue = false;
  142. }
  143. options.fields[field]['validators'][v][optionName] = optionValue;
  144. }
  145. }
  146. }
  147. }
  148. });
  149. this.options = $.extend(true, this.options, options);
  150. //console.log(this.options);
  151. for (var field in this.options.fields) {
  152. this._initField(field);
  153. }
  154. this._setLiveValidating();
  155. },
  156. /**
  157. * Init field
  158. *
  159. * @param {String} field The field name
  160. */
  161. _initField: function(field) {
  162. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  163. return;
  164. }
  165. this.dfds[field] = {};
  166. this.results[field] = {};
  167. var fields = this.getFieldElements(field);
  168. // We don't need to validate non-existing fields
  169. if (fields == null) {
  170. delete this.options.fields[field];
  171. delete this.dfds[field];
  172. return;
  173. }
  174. fields.attr('data-bv-field', field);
  175. // Create help block elements for showing the error messages
  176. var $field = $(fields[0]),
  177. $parent = $field.parents('.form-group'),
  178. // Allow user to indicate where the error messages are shown
  179. $message = this.options.fields[field].container ? $parent.find(this.options.fields[field].container) : this._getMessageContainer($field);
  180. $field.data('bootstrapValidator.messageContainer', $message);
  181. for (var validatorName in this.options.fields[field].validators) {
  182. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  183. delete this.options.fields[field].validators[validatorName];
  184. continue;
  185. }
  186. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  187. $('<small/>')
  188. .css('display', 'none')
  189. .attr('data-bv-validator', validatorName)
  190. .html(this.options.fields[field].validators[validatorName].message || this.options.fields[field].message || this.options.message)
  191. .addClass('help-block')
  192. .appendTo($message);
  193. }
  194. // Prepare the feedback icons
  195. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  196. if (this.options.feedbackIcons
  197. && this.options.feedbackIcons.validating && this.options.feedbackIcons.invalid && this.options.feedbackIcons.valid)
  198. {
  199. $parent.addClass('has-feedback');
  200. var $icon = $('<i/>').css('display', 'none').addClass('form-control-feedback').attr('data-bv-field', field).insertAfter($(fields[fields.length - 1]));
  201. // The feedback icon does not render correctly if there is no label
  202. // https://github.com/twbs/bootstrap/issues/12873
  203. if ($parent.find('label').length == 0) {
  204. $icon.css('top', 0);
  205. }
  206. }
  207. if (this.options.fields[field]['enabled'] == null) {
  208. this.options.fields[field]['enabled'] = true;
  209. }
  210. // Whenever the user change the field value, mark it as not validated yet
  211. var that = this,
  212. type = fields.attr('type'),
  213. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  214. fields.on(event + '.bootstrapValidator', function() {
  215. that.updateStatus($field, that.STATUS_NOT_VALIDATED, null);
  216. });
  217. },
  218. /**
  219. * Get the element to place the error messages
  220. *
  221. * @param {jQuery} $field The field element
  222. * @returns {jQuery}
  223. */
  224. _getMessageContainer: function($field) {
  225. var $parent = $field.parent();
  226. if ($parent.hasClass('form-group')) {
  227. return $parent;
  228. }
  229. var cssClasses = $parent.attr('class');
  230. if (!cssClasses) {
  231. return this._getMessageContainer($parent);
  232. }
  233. cssClasses = cssClasses.split(' ');
  234. var n = cssClasses.length;
  235. for (var i = 0; i < n; i++) {
  236. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i]) || /^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  237. return $parent;
  238. }
  239. }
  240. return this._getMessageContainer($parent);
  241. },
  242. /**
  243. * Enable live validating
  244. */
  245. _setLiveValidating: function() {
  246. if ('enabled' == this.options.live) {
  247. var that = this;
  248. for (var field in this.options.fields) {
  249. (function(f) {
  250. var fields = that.getFieldElements(f);
  251. if (fields) {
  252. var type = fields.attr('type'),
  253. event = ('radio' == type || 'checkbox' == type || 'file' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  254. fields.on(event + '.bootstrapValidator', function() {
  255. that.validateField(f);
  256. });
  257. }
  258. })(field);
  259. }
  260. }
  261. },
  262. /**
  263. * Disable/Enable submit buttons
  264. *
  265. * @param {Boolean} disabled
  266. */
  267. _disableSubmitButtons: function(disabled) {
  268. if (!disabled) {
  269. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  270. } else if (this.options.live != 'disabled') {
  271. // Don't disable if the live validating mode is disabled
  272. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  273. }
  274. },
  275. /**
  276. * Called when all validations are completed
  277. */
  278. _submit: function() {
  279. if (!this.isValid()) {
  280. if ('submitted' == this.options.live) {
  281. this.options.live = 'enabled';
  282. this._setLiveValidating();
  283. }
  284. // Focus to the first invalid field
  285. if (this.invalidField) {
  286. this.getFieldElements(this.invalidField).focus();
  287. }
  288. return;
  289. }
  290. this._disableSubmitButtons(true);
  291. // Call the custom submission if enabled
  292. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  293. // Turn off the submit handler, so user can call form.submit() inside their submitHandler method
  294. this.$form.off('submit.bootstrapValidator');
  295. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  296. } else {
  297. // Submit form
  298. this.$form.off('submit.bootstrapValidator').submit();
  299. }
  300. },
  301. // --- Public methods ---
  302. /**
  303. * Retrieve the field elements by given name
  304. *
  305. * @param {String} field The field name
  306. * @returns {null|jQuery[]}
  307. */
  308. getFieldElements: function(field) {
  309. var fields = this.$form.find(this.options.fields[field].selector || '[name="' + field + '"]');
  310. return (fields.length == 0) ? null : fields;
  311. },
  312. /**
  313. * Validate the form
  314. *
  315. * @return {BootstrapValidator}
  316. */
  317. validate: function() {
  318. if (!this.options.fields) {
  319. return this;
  320. }
  321. this._disableSubmitButtons(true);
  322. for (var field in this.options.fields) {
  323. this.validateField(field);
  324. }
  325. this._submit();
  326. return this;
  327. },
  328. /**
  329. * Validate given field
  330. *
  331. * @param {String} field The field name
  332. */
  333. validateField: function(field) {
  334. if (!this.options.fields[field]['enabled']) {
  335. return;
  336. }
  337. var that = this,
  338. fields = this.getFieldElements(field),
  339. $field = $(fields[0]),
  340. validators = this.options.fields[field].validators,
  341. validatorName,
  342. validateResult;
  343. // We don't need to validate disabled field
  344. if (fields.length == 1 && fields.is(':disabled')) {
  345. delete this.options.fields[field];
  346. delete this.dfds[field];
  347. return;
  348. }
  349. for (validatorName in validators) {
  350. if (this.dfds[field][validatorName]) {
  351. this.dfds[field][validatorName].reject();
  352. }
  353. // Don't validate field if it is already done
  354. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  355. continue;
  356. }
  357. this.results[field][validatorName] = this.STATUS_VALIDATING;
  358. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  359. if ('object' == typeof validateResult) {
  360. this.updateStatus($field, this.STATUS_VALIDATING, validatorName);
  361. this.dfds[field][validatorName] = validateResult;
  362. validateResult.done(function(isValid, v) {
  363. // v is validator name
  364. delete that.dfds[field][v];
  365. that.updateStatus($field, isValid ? that.STATUS_VALID : that.STATUS_INVALID, v);
  366. if (isValid && 'disabled' == that.options.live) {
  367. that._submit();
  368. }
  369. });
  370. } else if ('boolean' == typeof validateResult) {
  371. this.updateStatus($field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
  372. }
  373. }
  374. },
  375. /**
  376. * Check the form validity
  377. *
  378. * @returns {Boolean}
  379. */
  380. isValid: function() {
  381. var field, validatorName;
  382. for (field in this.results) {
  383. if (this.options.fields[field] == null || !this.options.fields[field]['enabled']) {
  384. continue;
  385. }
  386. for (validatorName in this.results[field]) {
  387. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  388. return false;
  389. }
  390. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  391. this.invalidField = field;
  392. return false;
  393. }
  394. }
  395. }
  396. return true;
  397. },
  398. /**
  399. * Update field status
  400. *
  401. * @param {String|jQuery} field The field name or field element
  402. * @param {String} status The status
  403. * Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID' or 'VALID'
  404. * @param {String|null} validatorName The validator name. If null, the method updates validity result for all validators
  405. * @return {BootstrapValidator}
  406. */
  407. updateStatus: function(field, status, validatorName) {
  408. var $field = ('string' == typeof field) ? this.getFieldElements(field) : field,
  409. that = this,
  410. field = $field.attr('data-bv-field'),
  411. $parent = $field.parents('.form-group'),
  412. $message = $field.data('bootstrapValidator.messageContainer'),
  413. $errors = $message.find('.help-block[data-bv-validator]'),
  414. $icon = $parent.find('.form-control-feedback[data-bv-field="' + field + '"]');
  415. // Update status
  416. if (validatorName) {
  417. this.results[field][validatorName] = status;
  418. } else {
  419. for (var v in this.options.fields[field].validators) {
  420. this.results[field][v] = status;
  421. }
  422. }
  423. // Show/hide error elements and feedback icons
  424. switch (status) {
  425. case this.STATUS_VALIDATING:
  426. this._disableSubmitButtons(true);
  427. $parent.removeClass('has-success').removeClass('has-error');
  428. // TODO: Show validating message
  429. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  430. if ($icon) {
  431. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).addClass(this.options.feedbackIcons.validating).show();
  432. }
  433. break;
  434. case this.STATUS_INVALID:
  435. this._disableSubmitButtons(true);
  436. $parent.removeClass('has-success').addClass('has-error');
  437. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').show() : $errors.show();
  438. if ($icon) {
  439. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.invalid).show();
  440. }
  441. break;
  442. case this.STATUS_VALID:
  443. validatorName ? $errors.filter('[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  444. // If the field is valid
  445. if ($errors.filter(function() {
  446. var display = $(this).css('display'), v = $(this).attr('data-bv-validator');
  447. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  448. }).length == 0
  449. ) {
  450. this._disableSubmitButtons(false);
  451. $parent.removeClass('has-error').addClass('has-success');
  452. if ($icon) {
  453. $icon.removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).addClass(this.options.feedbackIcons.valid).show();
  454. }
  455. }
  456. break;
  457. case this.STATUS_NOT_VALIDATED:
  458. default:
  459. this._disableSubmitButtons(false);
  460. $parent.removeClass('has-success').removeClass('has-error');
  461. validatorName ? $errors.filter('.help-block[data-bv-validator="' + validatorName + '"]').hide() : $errors.hide();
  462. if ($icon) {
  463. $icon.removeClass(this.options.feedbackIcons.valid).removeClass(this.options.feedbackIcons.invalid).removeClass(this.options.feedbackIcons.validating).hide();
  464. }
  465. break;
  466. }
  467. return this;
  468. },
  469. // Useful APIs which aren't used internally
  470. /**
  471. * Reset the form
  472. *
  473. * @param {Boolean} resetFormData Reset current form data
  474. * @return {BootstrapValidator}
  475. */
  476. resetForm: function(resetFormData) {
  477. var field, $field, type;
  478. for (field in this.options.fields) {
  479. this.dfds[field] = {};
  480. this.results[field] = {};
  481. $field = this.getFieldElements(field);
  482. // Mark field as not validated yet
  483. this.updateStatus($field, this.STATUS_NOT_VALIDATED, null);
  484. if (resetFormData) {
  485. type = $field.attr('type');
  486. ('radio' == type || 'checkbox' == type) ? $field.removeAttr('checked').removeAttr('selected') : $field.val('');
  487. }
  488. }
  489. this.invalidField = null;
  490. this.$submitButton = null;
  491. // Enable submit buttons
  492. this._disableSubmitButtons(false);
  493. return this;
  494. },
  495. /**
  496. * Enable/Disable all validators to given field
  497. *
  498. * @param {String} field The field name
  499. * @param {Boolean} enabled Enable/Disable field validators
  500. * @return {BootstrapValidator}
  501. */
  502. enableFieldValidators: function(field, enabled) {
  503. this.options.fields[field]['enabled'] = enabled;
  504. this.updateStatus(field, this.STATUS_NOT_VALIDATED, null);
  505. return this;
  506. }
  507. };
  508. // Plugin definition
  509. $.fn.bootstrapValidator = function(options) {
  510. return this.each(function() {
  511. var $this = $(this), data = $this.data('bootstrapValidator');
  512. if (!data) {
  513. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  514. }
  515. if ('string' == typeof options) {
  516. data[options]();
  517. }
  518. });
  519. };
  520. // Available validators
  521. $.fn.bootstrapValidator.validators = {};
  522. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  523. }(window.jQuery));
  524. ;(function($) {
  525. $.fn.bootstrapValidator.validators.base64 = {
  526. /**
  527. * Return true if the input value is a base 64 encoded string.
  528. *
  529. * @param {BootstrapValidator} validator The validator plugin instance
  530. * @param {jQuery} $field Field element
  531. * @param {Object} options Can consist of the following keys:
  532. * - message: The invalid message
  533. * @returns {Boolean}
  534. */
  535. validate: function(validator, $field, options) {
  536. var value = $field.val();
  537. if (value == '') {
  538. return true;
  539. }
  540. return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/.test(value);
  541. }
  542. };
  543. }(window.jQuery));
  544. ;(function($) {
  545. $.fn.bootstrapValidator.validators.between = {
  546. /**
  547. * Return true if the input value is between (strictly or not) two given numbers
  548. *
  549. * @param {BootstrapValidator} validator The validator plugin instance
  550. * @param {jQuery} $field Field element
  551. * @param {Object} options Can consist of the following keys:
  552. * - min
  553. * - max
  554. * - inclusive [optional]: Can be true or false. Default is true
  555. * - message: The invalid message
  556. * @returns {Boolean}
  557. */
  558. validate: function(validator, $field, options) {
  559. var value = $field.val();
  560. if (value == '') {
  561. return true;
  562. }
  563. value = parseFloat(value);
  564. return (options.inclusive === true)
  565. ? (value > options.min && value < options.max)
  566. : (value >= options.min && value <= options.max);
  567. }
  568. };
  569. }(window.jQuery));
  570. ;(function($) {
  571. $.fn.bootstrapValidator.validators.callback = {
  572. /**
  573. * Return result from the callback method
  574. *
  575. * @param {BootstrapValidator} validator The validator plugin instance
  576. * @param {jQuery} $field Field element
  577. * @param {Object} options Can consist of the following keys:
  578. * - callback: The callback method that passes 2 parameters:
  579. * callback: function(fieldValue, validator) {
  580. * // fieldValue is the value of field
  581. * // validator is instance of BootstrapValidator
  582. * }
  583. * - message: The invalid message
  584. * @returns {Boolean|Deferred}
  585. */
  586. validate: function(validator, $field, options) {
  587. var value = $field.val();
  588. if (options.callback && 'function' == typeof options.callback) {
  589. var dfd = new $.Deferred();
  590. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  591. return dfd;
  592. }
  593. return true;
  594. }
  595. };
  596. }(window.jQuery));
  597. ;(function($) {
  598. $.fn.bootstrapValidator.validators.choice = {
  599. html5Attributes: ['message', 'min', 'max'],
  600. /**
  601. * Check if the number of checked boxes are less or more than a given number
  602. *
  603. * @param {BootstrapValidator} validator The validator plugin instance
  604. * @param {jQuery} $field Field element
  605. * @param {Object} options Consists of following keys:
  606. * - min
  607. * - max
  608. * At least one of two keys is required
  609. * @returns {Boolean}
  610. */
  611. validate: function(validator, $field, options) {
  612. var numChoices = validator
  613. .getFieldElements($field.attr('data-bv-field'))
  614. .filter(':checked')
  615. .length;
  616. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  617. return false;
  618. }
  619. return true;
  620. }
  621. };
  622. }(window.jQuery));
  623. ;(function($) {
  624. $.fn.bootstrapValidator.validators.creditCard = {
  625. /**
  626. * Return true if the input value is valid credit card number
  627. * Based on https://gist.github.com/DiegoSalazar/4075533
  628. *
  629. * @param {BootstrapValidator} validator The validator plugin instance
  630. * @param {jQuery} $field Field element
  631. * @param {Object} options Can consist of the following key:
  632. * - message: The invalid message
  633. * @returns {Boolean}
  634. */
  635. validate: function(validator, $field, options) {
  636. var value = $field.val();
  637. if (value == '') {
  638. return true;
  639. }
  640. // Accept only digits, dashes or spaces
  641. if (/[^0-9-\s]+/.test(value)) {
  642. return false;
  643. }
  644. value = value.replace(/\D/g, '');
  645. // Validate the check sum
  646. // The Luhn Algorithm
  647. // http://en.wikipedia.org/wiki/Luhn
  648. var check = 0, digit = 0, even = false, length = value.length;
  649. for (var n = length - 1; n >= 0; n--) {
  650. digit = parseInt(value.charAt(n), 10);
  651. if (even) {
  652. if ((digit *= 2) > 9) {
  653. digit -= 9;
  654. }
  655. }
  656. check += digit;
  657. even = !even;
  658. }
  659. if ((check % 10) != 0) {
  660. return false;
  661. }
  662. // Validate the card number based on prefix (IIN ranges) and length
  663. var cards = {
  664. AMERICAN_EXPRESS: {
  665. length: [15],
  666. prefix: ['34', '37']
  667. },
  668. DINERS_CLUB: {
  669. length: [14],
  670. prefix: ['300', '301', '302', '303', '304', '305', '36']
  671. },
  672. DINERS_CLUB_US: {
  673. length: [16],
  674. prefix: ['54', '55']
  675. },
  676. DISCOVER: {
  677. length: [16],
  678. prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
  679. '62214', '62215', '62216', '62217', '62218', '62219',
  680. '6222', '6223', '6224', '6225', '6226', '6227', '6228',
  681. '62290', '62291', '622920', '622921', '622922', '622923',
  682. '622924', '622925', '644', '645', '646', '647', '648',
  683. '649', '65']
  684. },
  685. JCB: {
  686. length: [16],
  687. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  688. },
  689. LASER: {
  690. length: [16, 17, 18, 19],
  691. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  692. },
  693. MAESTRO: {
  694. length: [12, 13, 14, 15, 16, 17, 18, 19],
  695. prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
  696. },
  697. MASTERCARD: {
  698. length: [16],
  699. prefix: ['51', '52', '53', '54', '55']
  700. },
  701. SOLO: {
  702. length: [16, 18, 19],
  703. prefix: ['6334', '6767']
  704. },
  705. UNIONPAY: {
  706. length: [16, 17, 18, 19],
  707. prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
  708. '62215', '62216', '62217', '62218', '62219', '6222', '6223',
  709. '6224', '6225', '6226', '6227', '6228', '62290', '62291',
  710. '622920', '622921', '622922', '622923', '622924', '622925']
  711. },
  712. VISA: {
  713. length: [16],
  714. prefix: ['4']
  715. }
  716. };
  717. var type, i;
  718. for (type in cards) {
  719. for (i in cards[type]['prefix']) {
  720. if (value.substr(0, cards[type]['prefix'][i].length) == cards[type]['prefix'][i] // Check the prefix
  721. && cards[type]['length'].indexOf(value.length) != -1) // and length
  722. {
  723. return true;
  724. }
  725. }
  726. }
  727. return false;
  728. }
  729. };
  730. }(window.jQuery));
  731. ;(function($) {
  732. $.fn.bootstrapValidator.validators.cvv = {
  733. /**
  734. * Return true if the input value is a valid CVV number.
  735. *
  736. * @param {BootstrapValidator} validator The validator plugin instance
  737. * @param {jQuery} $field Field element
  738. * @param {Object} options Can consist of the following keys:
  739. * - creditCardField: The credit card number field. It can be null
  740. * - message: The invalid message
  741. * @returns {Boolean}
  742. */
  743. validate: function(validator, $field, options) {
  744. var value = $field.val();
  745. if (value == '') {
  746. return true;
  747. }
  748. if (!/^[0-9]{3,4}$/.test(value)) {
  749. return false;
  750. }
  751. if (!options.creditCardField) {
  752. return true;
  753. }
  754. // Get the credit card number
  755. var creditCard = validator.getFieldElements(options.creditCardField).val();
  756. if (creditCard == '') {
  757. return true;
  758. }
  759. // Supported credit card types
  760. var cards = {
  761. AMERICAN_EXPRESS: {
  762. length: [15],
  763. prefix: ['34', '37']
  764. },
  765. DINERS_CLUB: {
  766. length: [14],
  767. prefix: ['300', '301', '302', '303', '304', '305', '36']
  768. },
  769. DINERS_CLUB_US: {
  770. length: [16],
  771. prefix: ['54', '55']
  772. },
  773. DISCOVER: {
  774. length: [16],
  775. prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
  776. '62214', '62215', '62216', '62217', '62218', '62219',
  777. '6222', '6223', '6224', '6225', '6226', '6227', '6228',
  778. '62290', '62291', '622920', '622921', '622922', '622923',
  779. '622924', '622925', '644', '645', '646', '647', '648',
  780. '649', '65']
  781. },
  782. JCB: {
  783. length: [16],
  784. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  785. },
  786. LASER: {
  787. length: [16, 17, 18, 19],
  788. prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
  789. },
  790. MAESTRO: {
  791. length: [12, 13, 14, 15, 16, 17, 18, 19],
  792. prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
  793. },
  794. MASTERCARD: {
  795. length: [16],
  796. prefix: ['51', '52', '53', '54', '55']
  797. },
  798. SOLO: {
  799. length: [16, 18, 19],
  800. prefix: ['6334', '6767']
  801. },
  802. UNIONPAY: {
  803. length: [16, 17, 18, 19],
  804. prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
  805. '62215', '62216', '62217', '62218', '62219', '6222', '6223',
  806. '6224', '6225', '6226', '6227', '6228', '62290', '62291',
  807. '622920', '622921', '622922', '622923', '622924', '622925']
  808. },
  809. VISA: {
  810. length: [16],
  811. prefix: ['4']
  812. }
  813. };
  814. var type, i, creditCardType = null;
  815. for (type in cards) {
  816. for (i in cards[type]['prefix']) {
  817. if (creditCard.substr(0, cards[type]['prefix'][i].length) == cards[type]['prefix'][i] // Check the prefix
  818. && cards[type]['length'].indexOf(creditCard.length) != -1) // and length
  819. {
  820. creditCardType = type;
  821. break;
  822. }
  823. }
  824. }
  825. return (creditCardType == null)
  826. ? false
  827. : (('AMERICAN_EXPRESS' == creditCardType) ? (value.length == 4) : (value.length == 3));
  828. }
  829. };
  830. }(window.jQuery));
  831. ;(function($) {
  832. $.fn.bootstrapValidator.validators.date = {
  833. html5Attributes: ['message', 'format'],
  834. /**
  835. * Return true if the input value is valid date
  836. *
  837. * @param {BootstrapValidator} validator The validator plugin instance
  838. * @param {jQuery} $field Field element
  839. * @param {Object} options Can consist of the following keys:
  840. * - format: The date format. Default is MM/DD/YYYY
  841. * Support the following formats:
  842. * YYYY/DD/MM
  843. * YYYY/DD/MM h:m A
  844. * YYYY/MM/DD
  845. * YYYY/MM/DD h:m A
  846. *
  847. * YYYY-DD-MM
  848. * YYYY-DD-MM h:m A
  849. * YYYY-MM-DD
  850. * YYYY-MM-DD h:m A
  851. *
  852. * MM/DD/YYYY
  853. * MM/DD/YYYY h:m A
  854. * DD/MM/YYYY
  855. * DD/MM/YYYY h:m A
  856. *
  857. * MM-DD-YYYY
  858. * MM-DD-YYYY h:m A
  859. * DD-MM-YYYY
  860. * DD-MM-YYYY h:m A
  861. * - message: The invalid message
  862. * @returns {Boolean}
  863. */
  864. validate: function(validator, $field, options) {
  865. var value = $field.val();
  866. if (value == '') {
  867. return true;
  868. }
  869. // Determine the separator
  870. options.format = options.format || 'MM/DD/YYYY';
  871. var separator = (options.format.indexOf('/') != -1)
  872. ? '/'
  873. : ((options.format.indexOf('-') != -1) ? '-' : null);
  874. if (separator == null) {
  875. return false;
  876. }
  877. var month, day, year, minutes = null, hours = null, matches;
  878. switch (true) {
  879. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/DD/MM'):
  880. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-DD-MM'):
  881. year = matches[1]; day = matches[2]; month = matches[3];
  882. break;
  883. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'DD/MM/YYYY'):
  884. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'DD-MM-YYYY'):
  885. day = matches[1]; month = matches[2]; year = matches[3];
  886. break;
  887. case (separator == '/' && (matches = value.match(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/i)) && options.format == 'YYYY/MM/DD'):
  888. case (separator == '-' && (matches = value.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/i)) && options.format == 'YYYY-MM-DD'):
  889. year = matches[1]; month = matches[2]; day = matches[3];
  890. break;
  891. case (separator == '/' && (matches = value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/i)) && options.format == 'MM/DD/YYYY'):
  892. case (separator == '-' && (matches = value.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/i)) && options.format == 'MM-DD-YYYY'):
  893. month = matches[1]; day = matches[2]; year = matches[3];
  894. break;
  895. 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'):
  896. 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'):
  897. year = matches[1]; day = matches[2]; month = matches[3]; hours = matches[4]; minutes = matches[5];
  898. break;
  899. 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'):
  900. 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'):
  901. day = matches[1]; month = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  902. break;
  903. 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'):
  904. 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'):
  905. year = matches[1]; month = matches[2]; day = matches[3]; hours = matches[4]; minutes = matches[5];
  906. break;
  907. 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'):
  908. 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'):
  909. month = matches[1]; day = matches[2]; year = matches[3]; hours = matches[4]; minutes = matches[5];
  910. break;
  911. default:
  912. return false;
  913. }
  914. // Validate hours and minutes
  915. if (hours && minutes) {
  916. hours = parseInt(hours, 10);
  917. minutes = parseInt(minutes, 10);
  918. if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
  919. return false;
  920. }
  921. }
  922. // Validate day, month, and year
  923. day = parseInt(day, 10);
  924. month = parseInt(month, 10);
  925. year = parseInt(year, 10);
  926. if (year < 1000 || year > 9999 || month == 0 || month > 12) {
  927. return false;
  928. }
  929. var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  930. // Update the number of days in Feb of leap year
  931. if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
  932. numDays[1] = 29;
  933. }
  934. // Check the day
  935. return (day > 0 && day <= numDays[month - 1]);
  936. }
  937. };
  938. }(window.jQuery));
  939. ;(function($) {
  940. $.fn.bootstrapValidator.validators.different = {
  941. html5Attributes: ['message', 'field'],
  942. /**
  943. * Return true if the input value is different with given field's value
  944. *
  945. * @param {BootstrapValidator} validator The validator plugin instance
  946. * @param {jQuery} $field Field element
  947. * @param {Object} options Consists of the following key:
  948. * - field: The name of field that will be used to compare with current one
  949. * - message: The invalid message
  950. * @returns {Boolean}
  951. */
  952. validate: function(validator, $field, options) {
  953. var value = $field.val();
  954. if (value == '') {
  955. return true;
  956. }
  957. var compareWith = validator.getFieldElements(options.field);
  958. if (compareWith == null) {
  959. return true;
  960. }
  961. if (value != compareWith.val()) {
  962. validator.updateStatus(compareWith, validator.STATUS_VALID, 'different');
  963. return true;
  964. } else {
  965. return false;
  966. }
  967. }
  968. };
  969. }(window.jQuery));
  970. ;(function($) {
  971. $.fn.bootstrapValidator.validators.digits = {
  972. /**
  973. * Return true if the input value contains digits only
  974. *
  975. * @param {BootstrapValidator} validator Validate plugin instance
  976. * @param {jQuery} $field Field element
  977. * @param {Object} options
  978. * @returns {Boolean}
  979. */
  980. validate: function(validator, $field, options) {
  981. var value = $field.val();
  982. if (value == '') {
  983. return true;
  984. }
  985. return /^\d+$/.test(value);
  986. }
  987. }
  988. }(window.jQuery));
  989. ;(function($) {
  990. $.fn.bootstrapValidator.validators.emailAddress = {
  991. enableByHtml5: function($field) {
  992. return ('email' == $field.attr('type'));
  993. },
  994. /**
  995. * Return true if and only if the input value is a valid email address
  996. *
  997. * @param {BootstrapValidator} validator Validate plugin instance
  998. * @param {jQuery} $field Field element
  999. * @param {Object} options
  1000. * @returns {Boolean}
  1001. */
  1002. validate: function(validator, $field, options) {
  1003. var value = $field.val();
  1004. if (value == '') {
  1005. return true;
  1006. }
  1007. // Email address regular expression
  1008. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  1009. 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,}))$/;
  1010. return emailRegExp.test(value);
  1011. }
  1012. }
  1013. }(window.jQuery));
  1014. ;(function($) {
  1015. $.fn.bootstrapValidator.validators.greaterThan = {
  1016. html5Attributes: ['message', 'value', 'inclusive'],
  1017. enableByHtml5: function($field) {
  1018. var min = $field.attr('min');
  1019. if (min) {
  1020. return {
  1021. value: min
  1022. };
  1023. }
  1024. return false;
  1025. },
  1026. /**
  1027. * Return true if the input value is greater than or equals to given number
  1028. *
  1029. * @param {BootstrapValidator} validator Validate plugin instance
  1030. * @param {jQuery} $field Field element
  1031. * @param {Object} options Can consist of the following keys:
  1032. * - value: The number used to compare to
  1033. * - inclusive [optional]: Can be true or false. Default is true
  1034. * - message: The invalid message
  1035. * @returns {Boolean}
  1036. */
  1037. validate: function(validator, $field, options) {
  1038. var value = $field.val();
  1039. if (value == '') {
  1040. return true;
  1041. }
  1042. value = parseFloat(value);
  1043. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  1044. }
  1045. }
  1046. }(window.jQuery));
  1047. ;(function($) {
  1048. $.fn.bootstrapValidator.validators.hexColor = {
  1049. /**
  1050. * Return true if the input value is a valid hex color
  1051. *
  1052. * @param {BootstrapValidator} validator The validator plugin instance
  1053. * @param {jQuery} $field Field element
  1054. * @param {Object} options Can consist of the following keys:
  1055. * - message: The invalid message
  1056. * @returns {Boolean}
  1057. */
  1058. validate: function(validator, $field, options) {
  1059. var value = $field.val();
  1060. if (value == '') {
  1061. return true;
  1062. }
  1063. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  1064. }
  1065. };
  1066. }(window.jQuery));
  1067. ;(function($) {
  1068. $.fn.bootstrapValidator.validators.identical = {
  1069. html5Attributes: ['message', 'field'],
  1070. /**
  1071. * Check if input value equals to value of particular one
  1072. *
  1073. * @param {BootstrapValidator} validator The validator plugin instance
  1074. * @param {jQuery} $field Field element
  1075. * @param {Object} options Consists of the following key:
  1076. * - field: The name of field that will be used to compare with current one
  1077. * @returns {Boolean}
  1078. */
  1079. validate: function(validator, $field, options) {
  1080. var value = $field.val();
  1081. if (value == '') {
  1082. return true;
  1083. }
  1084. var compareWith = validator.getFieldElements(options.field);
  1085. if (compareWith == null) {
  1086. return true;
  1087. }
  1088. if (value == compareWith.val()) {
  1089. validator.updateStatus(compareWith, validator.STATUS_VALID, 'identical');
  1090. return true;
  1091. } else {
  1092. return false;
  1093. }
  1094. }
  1095. };
  1096. }(window.jQuery));
  1097. ;(function($) {
  1098. $.fn.bootstrapValidator.validators.ip = {
  1099. html5Attributes: ['message', 'ipv4', 'ipv6'],
  1100. /**
  1101. * Return true if the input value is a IP address.
  1102. *
  1103. * @param {BootstrapValidator} validator The validator plugin instance
  1104. * @param {jQuery} $field Field element
  1105. * @param {Object} options Can consist of the following keys:
  1106. * - ipv4: Enable IPv4 validator, default to true
  1107. * - ipv6: Enable IPv6 validator, default to true
  1108. * - message: The invalid message
  1109. * @returns {Boolean}
  1110. */
  1111. validate: function(validator, $field, options) {
  1112. var value = $field.val();
  1113. if (value == '') {
  1114. return true;
  1115. }
  1116. options = $.extend({}, { ipv4: true, ipv6: true }, options);
  1117. if (options.ipv4) {
  1118. return /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(value);
  1119. } else if (options.ipv6) {
  1120. return /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(str);
  1121. }
  1122. return false;
  1123. }
  1124. };
  1125. }(window.jQuery));
  1126. ;(function($) {
  1127. $.fn.bootstrapValidator.validators.isbn = {
  1128. /**
  1129. * Return true if the input value is a valid ISBN 10 or ISBN 13 number
  1130. *
  1131. * @param {BootstrapValidator} validator The validator plugin instance
  1132. * @param {jQuery} $field Field element
  1133. * @param {Object} options Can consist of the following keys:
  1134. * - message: The invalid message
  1135. * @returns {Boolean}
  1136. */
  1137. validate: function(validator, $field, options) {
  1138. var value = $field.val();
  1139. if (value == '') {
  1140. return true;
  1141. }
  1142. // Replace all special characters except digits and X
  1143. value = value.replace(/[^\dX]/gi, '');
  1144. var chars = value.split(''),
  1145. sum = 0,
  1146. checksum;
  1147. // See http://en.wikipedia.org/wiki/International_Standard_Book_Number
  1148. switch (chars.length) {
  1149. // ISBN 10
  1150. case 10:
  1151. sum = 0;
  1152. for (var i = 0; i < 9; i++) {
  1153. sum += ((10 - i) * parseInt(chars[i]));
  1154. }
  1155. checksum = 11 - (sum % 11);
  1156. if (checksum == 11) {
  1157. checksum = 0;
  1158. } else if (checksum == 10) {
  1159. checksum = 'X';
  1160. }
  1161. return (checksum == chars[9]);
  1162. // ISBN 13
  1163. case 13:
  1164. sum = 0;
  1165. for (var i = 0; i < 12; i++) {
  1166. sum += ((i % 2 == 0) ? parseInt(chars[i]) : (parseInt(chars[i]) * 3));
  1167. }
  1168. checksum = 10 - (sum % 10);
  1169. if (checksum == 10) {
  1170. checksum = '0';
  1171. }
  1172. return (checksum == chars[12]);
  1173. default:
  1174. return false;
  1175. }
  1176. }
  1177. };
  1178. }(window.jQuery));
  1179. ;(function($) {
  1180. $.fn.bootstrapValidator.validators.lessThan = {
  1181. html5Attributes: ['message', 'value', 'inclusive'],
  1182. enableByHtml5: function($field) {
  1183. var max = $field.attr('max');
  1184. if (max) {
  1185. return {
  1186. value: max
  1187. };
  1188. }
  1189. return false;
  1190. },
  1191. /**
  1192. * Return true if the input value is less than or equal to given number
  1193. *
  1194. * @param {BootstrapValidator} validator The validator plugin instance
  1195. * @param {jQuery} $field Field element
  1196. * @param {Object} options Can consist of the following keys:
  1197. * - value: The number used to compare to
  1198. * - inclusive [optional]: Can be true or false. Default is true
  1199. * - message: The invalid message
  1200. * @returns {Boolean}
  1201. */
  1202. validate: function(validator, $field, options) {
  1203. var value = $field.val();
  1204. if (value == '') {
  1205. return true;
  1206. }
  1207. value = parseFloat(value);
  1208. return (options.inclusive === false) ? (value <= options.value) : (value < options.value);
  1209. }
  1210. };
  1211. }(window.jQuery));
  1212. ;(function($) {
  1213. $.fn.bootstrapValidator.validators.mac = {
  1214. /**
  1215. * Return true if the input value is a MAC address.
  1216. *
  1217. * @param {BootstrapValidator} validator The validator plugin instance
  1218. * @param {jQuery} $field Field element
  1219. * @param {Object} options Can consist of the following keys:
  1220. * - message: The invalid message
  1221. * @returns {Boolean}
  1222. */
  1223. validate: function(validator, $field, options) {
  1224. var value = $field.val();
  1225. if (value == '') {
  1226. return true;
  1227. }
  1228. return /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/.test(value);
  1229. }
  1230. };
  1231. }(window.jQuery));
  1232. ;(function($) {
  1233. $.fn.bootstrapValidator.validators.notEmpty = {
  1234. enableByHtml5: function($field) {
  1235. var required = $field.attr('required') + '';
  1236. return ('required' == required || 'true' == required);
  1237. },
  1238. /**
  1239. * Check if input value is empty or not
  1240. *
  1241. * @param {BootstrapValidator} validator The validator plugin instance
  1242. * @param {jQuery} $field Field element
  1243. * @param {Object} options
  1244. * @returns {Boolean}
  1245. */
  1246. validate: function(validator, $field, options) {
  1247. var type = $field.attr('type');
  1248. if ('radio' == type || 'checkbox' == type) {
  1249. return validator
  1250. .getFieldElements($field.attr('data-bv-field'))
  1251. .filter(':checked')
  1252. .length > 0;
  1253. }
  1254. return $.trim($field.val()) != '';
  1255. }
  1256. };
  1257. }(window.jQuery));
  1258. ;(function($) {
  1259. $.fn.bootstrapValidator.validators.phone = {
  1260. html5Attributes: ['message', 'country'],
  1261. /**
  1262. * Return true if the input value contains a valid US phone number only
  1263. *
  1264. * @param {BootstrapValidator} validator Validate plugin instance
  1265. * @param {jQuery} $field Field element
  1266. * @param {Object} options Consist of key:
  1267. * - message: The invalid message
  1268. * - country: The ISO 3166 country code
  1269. * Currently it only supports United State (US) country
  1270. * @returns {Boolean}
  1271. */
  1272. validate: function(validator, $field, options) {
  1273. var value = $field.val();
  1274. if (value == '') {
  1275. return true;
  1276. }
  1277. options.country = options.country || 'US';
  1278. switch (options.country.toUpperCase()) {
  1279. case 'US':
  1280. default:
  1281. value = value.replace(/\(|\)|\s+/g, '');
  1282. return (/^(?:1\-?)?(\d{3})[\-\.]?(\d{3})[\-\.]?(\d{4})$/).test(value);
  1283. }
  1284. }
  1285. }
  1286. }(window.jQuery));
  1287. ;(function($) {
  1288. $.fn.bootstrapValidator.validators.regexp = {
  1289. html5Attributes: ['message', 'regexp'],
  1290. enableByHtml5: function($field) {
  1291. var pattern = $field.attr('pattern');
  1292. if (pattern) {
  1293. return {
  1294. regexp: pattern
  1295. };
  1296. }
  1297. return false;
  1298. },
  1299. /**
  1300. * Check if the element value matches given regular expression
  1301. *
  1302. * @param {BootstrapValidator} validator The validator plugin instance
  1303. * @param {jQuery} $field Field element
  1304. * @param {Object} options Consists of the following key:
  1305. * - regexp: The regular expression you need to check
  1306. * @returns {Boolean}
  1307. */
  1308. validate: function(validator, $field, options) {
  1309. var value = $field.val();
  1310. if (value == '') {
  1311. return true;
  1312. }
  1313. var regexp = ('string' == typeof options.regexp) ? new RegExp(options.regexp) : options.regexp;
  1314. return regexp.test(value);
  1315. }
  1316. };
  1317. }(window.jQuery));
  1318. ;(function($) {
  1319. $.fn.bootstrapValidator.validators.remote = {
  1320. html5Attributes: ['message', 'url'],
  1321. /**
  1322. * Request a remote server to check the input value
  1323. *
  1324. * @param {BootstrapValidator} validator Plugin instance
  1325. * @param {jQuery} $field Field element
  1326. * @param {Object} options Can consist of the following keys:
  1327. * - url
  1328. * - data [optional]: By default, it will take the value
  1329. * {
  1330. * <fieldName>: <fieldValue>
  1331. * }
  1332. * - message: The invalid message
  1333. * @returns {Boolean|Deferred}
  1334. */
  1335. validate: function(validator, $field, options) {
  1336. var value = $field.val();
  1337. if (value == '') {
  1338. return true;
  1339. }
  1340. var name = $field.attr('data-bv-field'), data = options.data;
  1341. if (data == null) {
  1342. data = {};
  1343. }
  1344. // Support dynamic data
  1345. if ('function' == typeof data) {
  1346. data = data.call(this, validator);
  1347. }
  1348. data[name] = value;
  1349. var dfd = new $.Deferred();
  1350. var xhr = $.ajax({
  1351. type: 'POST',
  1352. url: options.url,
  1353. dataType: 'json',
  1354. data: data
  1355. });
  1356. xhr.then(function(response) {
  1357. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  1358. });
  1359. dfd.fail(function() {
  1360. xhr.abort();
  1361. });
  1362. return dfd;
  1363. }
  1364. };
  1365. }(window.jQuery));
  1366. ;(function($) {
  1367. $.fn.bootstrapValidator.validators.step = {
  1368. /**
  1369. * Return true if the input value is valid step one
  1370. *
  1371. * @param {BootstrapValidator} validator The validator plugin instance
  1372. * @param {jQuery} $field Field element
  1373. * @param {Object} options Can consist of the following keys:
  1374. * - baseValue: The base value
  1375. * - step: The step
  1376. * - message: The invalid message
  1377. * @returns {Boolean}
  1378. */
  1379. validate: function(validator, $field, options) {
  1380. var value = $field.val();
  1381. if (value == '') {
  1382. return true;
  1383. }
  1384. options = $.extend({}, { baseValue: 0, step: 1 }, options);
  1385. value = parseFloat(value);
  1386. if (isNaN(value) || !isFinite(value)) {
  1387. return false;
  1388. }
  1389. var round = function(x, precision) {
  1390. var m = Math.pow(10, precision);
  1391. x = x * m;
  1392. var sign = (x > 0) | -(x < 0),
  1393. isHalf = (x % 1 === 0.5 * sign);
  1394. if (isHalf) {
  1395. return (Math.floor(x) + (sign > 0)) / m;
  1396. } else {
  1397. return Math.round(x) / m;
  1398. }
  1399. },
  1400. floatMod = function(x, y) {
  1401. if (y == 0.0) {
  1402. return 1.0;
  1403. }
  1404. var dotX = (x + '').split('.'),
  1405. dotY = (y + '').split('.'),
  1406. precision = ((dotX.length == 1) ? 0 : dotX[1].length) + ((dotY.length == 1) ? 0 : dotY[1].length);
  1407. return round(x - y * Math.floor(x / y), precision);
  1408. };
  1409. var mod = floatMod(value - options.baseValue, options.step);
  1410. return (mod == 0.0 || mod == options.step);
  1411. }
  1412. };
  1413. }(window.jQuery));
  1414. ;(function($) {
  1415. $.fn.bootstrapValidator.validators.stringLength = {
  1416. html5Attributes: ['message', 'min', 'max'],
  1417. /**
  1418. * Check if the length of element value is less or more than given number
  1419. *
  1420. * @param {BootstrapValidator} validator The validator plugin instance
  1421. * @param {jQuery} $field Field element
  1422. * @param {Object} options Consists of following keys:
  1423. * - min
  1424. * - max
  1425. * At least one of two keys is required
  1426. * @returns {Boolean}
  1427. */
  1428. validate: function(validator, $field, options) {
  1429. var value = $field.val();
  1430. if (value == '') {
  1431. return true;
  1432. }
  1433. var length = $.trim(value).length;
  1434. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  1435. return false;
  1436. }
  1437. return true;
  1438. }
  1439. };
  1440. }(window.jQuery));
  1441. ;(function($) {
  1442. $.fn.bootstrapValidator.validators.uri = {
  1443. enableByHtml5: function($field) {
  1444. return ('url' == $field.attr('type'));
  1445. },
  1446. /**
  1447. * Return true if the input value is a valid URL
  1448. *
  1449. * @param {BootstrapValidator} validator The validator plugin instance
  1450. * @param {jQuery} $field Field element
  1451. * @param {Object} options
  1452. * @returns {Boolean}
  1453. */
  1454. validate: function(validator, $field, options) {
  1455. var value = $field.val();
  1456. if (value == '') {
  1457. return true;
  1458. }
  1459. // Credit to https://gist.github.com/dperini/729294
  1460. //
  1461. // Regular Expression for URL validation
  1462. //
  1463. // Author: Diego Perini
  1464. // Updated: 2010/12/05
  1465. //
  1466. // the regular expression composed & commented
  1467. // could be easily tweaked for RFC compliance,
  1468. // it was expressly modified to fit & satisfy
  1469. // these test for an URL shortener:
  1470. //
  1471. // http://mathiasbynens.be/demo/url-regex
  1472. //
  1473. // Notes on possible differences from a standard/generic validation:
  1474. //
  1475. // - utf-8 char class take in consideration the full Unicode range
  1476. // - TLDs have been made mandatory so single names like "localhost" fails
  1477. // - protocols have been restricted to ftp, http and https only as requested
  1478. //
  1479. // Changes:
  1480. //
  1481. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  1482. // first and last IP address of each class is considered invalid
  1483. // (since they are broadcast/network addresses)
  1484. //
  1485. // - Added exclusion of private, reserved and/or local networks ranges
  1486. //
  1487. // Compressed one-line versions:
  1488. //
  1489. // Javascript version
  1490. //
  1491. // /^(?:(?: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
  1492. //
  1493. // PHP version
  1494. //
  1495. // _^(?:(?: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
  1496. var urlExp = new RegExp(
  1497. "^" +
  1498. // protocol identifier
  1499. "(?:(?:https?|ftp)://)" +
  1500. // user:pass authentication
  1501. "(?:\\S+(?::\\S*)?@)?" +
  1502. "(?:" +
  1503. // IP address exclusion
  1504. // private & local networks
  1505. "(?!10(?:\\.\\d{1,3}){3})" +
  1506. "(?!127(?:\\.\\d{1,3}){3})" +
  1507. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  1508. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  1509. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  1510. // IP address dotted notation octets
  1511. // excludes loopback network 0.0.0.0
  1512. // excludes reserved space >= 224.0.0.0
  1513. // excludes network & broacast addresses
  1514. // (first & last IP address of each class)
  1515. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  1516. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  1517. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  1518. "|" +
  1519. // host name
  1520. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  1521. // domain name
  1522. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  1523. // TLD identifier
  1524. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  1525. ")" +
  1526. // port number
  1527. "(?::\\d{2,5})?" +
  1528. // resource path
  1529. "(?:/[^\\s]*)?" +
  1530. "$", "i"
  1531. );
  1532. return urlExp.test(value);
  1533. }
  1534. };
  1535. }(window.jQuery));
  1536. ;(function($) {
  1537. $.fn.bootstrapValidator.validators.zipCode = {
  1538. html5Attributes: ['message', 'country'],
  1539. /**
  1540. * Return true if and only if the input value is a valid country zip code
  1541. *
  1542. * @param {BootstrapValidator} validator The validator plugin instance
  1543. * @param {jQuery} $field Field element
  1544. * @param {Object} options Consist of key:
  1545. * - message: The invalid message
  1546. * - country: The ISO 3166 country code
  1547. *
  1548. * Currently it supports the following countries:
  1549. * - US (United State)
  1550. * - DK (Denmark)
  1551. * - SE (Sweden)
  1552. * @returns {Boolean}
  1553. */
  1554. validate: function(validator, $field, options) {
  1555. var value = $field.val();
  1556. if (value == '' || !options.country) {
  1557. return true;
  1558. }
  1559. options.country = options.country || 'US';
  1560. switch (options.country.toUpperCase()) {
  1561. case 'DK':
  1562. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  1563. case 'SE':
  1564. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  1565. case 'US':
  1566. default:
  1567. return /^\d{5}([\-]\d{4})?$/.test(value);
  1568. }
  1569. }
  1570. };
  1571. }(window.jQuery));