bootstrapValidator.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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.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. // 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 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. feedbackIcons: false,
  39. // The submit buttons selector
  40. // These buttons will be disabled to prevent the valid form from multiple submissions
  41. submitButtons: 'button[type="submit"]',
  42. // The custom submit handler
  43. // It will prevent the form from the default submission
  44. //
  45. // submitHandler: function(validator, form) {
  46. // - validator is the BootstrapValidator instance
  47. // - form is the jQuery object present the current form
  48. // }
  49. submitHandler: null,
  50. // Live validating option
  51. // Can be one of 3 values:
  52. // - enabled: The plugin validates fields as soon as they are changed
  53. // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
  54. // - submitted: The live validating is enabled after the form is submitted
  55. live: 'enabled',
  56. // Map the field name with validator rules
  57. fields: null
  58. };
  59. BootstrapValidator.prototype = {
  60. constructor: BootstrapValidator,
  61. /**
  62. * Init form
  63. */
  64. _init: function() {
  65. if (this.options.fields == null) {
  66. return;
  67. }
  68. var that = this;
  69. this.$form
  70. // Disable client side validation in HTML 5
  71. .attr('novalidate', 'novalidate')
  72. .addClass(this.options.elementClass)
  73. // Disable the default submission first
  74. .on('submit.bootstrapValidator', function(e) {
  75. e.preventDefault();
  76. that.validate();
  77. })
  78. .find(this.options.submitButtons)
  79. .on('click', function() {
  80. that.$submitButton = $(this);
  81. });
  82. for (var field in this.options.fields) {
  83. this._initField(field);
  84. }
  85. this._setLiveValidating();
  86. },
  87. /**
  88. * Init field
  89. *
  90. * @param {String} field The field name
  91. */
  92. _initField: function(field) {
  93. if (this.options.fields[field] == null || this.options.fields[field].validators == null) {
  94. return;
  95. }
  96. this.dfds[field] = {};
  97. this.results[field] = {};
  98. var fields = this.$form.find('[name="' + field + '"]');
  99. // We don't need to validate ...
  100. if (fields.length == 0 // ... non-existing fields
  101. || (fields.length == 1 && fields.is(':disabled'))) // ... disabled field
  102. {
  103. delete this.options.fields[field];
  104. delete this.dfds[field];
  105. return;
  106. }
  107. // Create a help block element for showing the error
  108. var $field = $(fields[0]),
  109. $parent = $field.parents('.form-group'),
  110. // Calculate the number of columns of the label/field element
  111. // Then set offset to the help block element
  112. label, cssClasses, offset, size;
  113. if (label = $parent.find('label').get(0)) {
  114. // The default Bootstrap form don't require class for label (http://getbootstrap.com/css/#forms)
  115. if (cssClasses = $(label).attr('class')) {
  116. cssClasses = cssClasses.split(' ');
  117. for (var i = 0; i < cssClasses.length; i++) {
  118. if (/^col-(xs|sm|md|lg)-\d+$/.test(cssClasses[i])) {
  119. offset = cssClasses[i].substr(7);
  120. size = cssClasses[i].substr(4, 2);
  121. break;
  122. }
  123. }
  124. }
  125. } else if (cssClasses = $parent.children().eq(0).attr('class')) {
  126. cssClasses = cssClasses.split(' ');
  127. for (var i = 0; i < cssClasses.length; i++) {
  128. if (/^col-(xs|sm|md|lg)-offset-\d+$/.test(cssClasses[i])) {
  129. offset = cssClasses[i].substr(14);
  130. size = cssClasses[i].substr(4, 2);
  131. break;
  132. }
  133. }
  134. }
  135. if (size && offset) {
  136. for (var validatorName in this.options.fields[field].validators) {
  137. if (!$.fn.bootstrapValidator.validators[validatorName]) {
  138. delete this.options.fields[field].validators[validatorName];
  139. continue;
  140. }
  141. this.results[field][validatorName] = this.STATUS_NOT_VALIDATED;
  142. $('<small/>')
  143. .css('display', 'none')
  144. .attr('data-bs-validator', validatorName)
  145. .addClass('help-block')
  146. .addClass(['col-', size, '-offset-', offset].join(''))
  147. .addClass(['col-', size, '-', this.options.columns - offset].join(''))
  148. .appendTo($parent);
  149. }
  150. }
  151. // Prepare the feedback icons
  152. // Available from Bootstrap 3.1 (http://getbootstrap.com/css/#forms-control-validation)
  153. if (this.options.feedbackIcons) {
  154. $parent.addClass('has-feedback');
  155. $('<span/>').css('display', 'none').addClass('glyphicon form-control-feedback').insertAfter($(fields[fields.length - 1]));
  156. }
  157. },
  158. /**
  159. * Enable live validating
  160. */
  161. _setLiveValidating: function() {
  162. if ('enabled' == this.options.live) {
  163. var that = this;
  164. for (var field in this.options.fields) {
  165. (function(f) {
  166. var fields = that.getFieldElements(f);
  167. if (fields) {
  168. var type = fields.attr('type'),
  169. event = ('radio' == type || 'checkbox' == type || 'SELECT' == fields[0].tagName) ? 'change' : 'keyup';
  170. fields.on(event, function() {
  171. // Whenever the user change the field value, make it as not validated yet
  172. for (var v in that.options.fields[f].validators) {
  173. that.results[f][v] = that.STATUS_NOT_VALIDATED;
  174. }
  175. that.validateField(f);
  176. });
  177. }
  178. })(field);
  179. }
  180. }
  181. },
  182. /**
  183. * Disable/Enable submit buttons
  184. *
  185. * @param {Boolean} disabled
  186. */
  187. _disableSubmitButtons: function(disabled) {
  188. if (!disabled) {
  189. this.$form.find(this.options.submitButtons).removeAttr('disabled');
  190. } else if (this.options.live != 'disabled') {
  191. // Don't disable if the live validating mode is disabled
  192. this.$form.find(this.options.submitButtons).attr('disabled', 'disabled');
  193. }
  194. },
  195. /**
  196. * Called when all validations are completed
  197. */
  198. _submit: function() {
  199. if (!this.isValid()) {
  200. if ('submitted' == this.options.live) {
  201. this.options.live = 'enabled';
  202. this._setLiveValidating();
  203. }
  204. // Focus to the first invalid field
  205. if (this.invalidField) {
  206. this.getFieldElements(this.invalidField).focus();
  207. }
  208. return;
  209. }
  210. this._disableSubmitButtons(true);
  211. // Call the custom submission if enabled
  212. if (this.options.submitHandler && 'function' == typeof this.options.submitHandler) {
  213. this.options.submitHandler.call(this, this, this.$form, this.$submitButton);
  214. } else {
  215. // Submit form
  216. this.$form.off('submit.bootstrapValidator').submit();
  217. }
  218. },
  219. // --- Public methods ---
  220. /**
  221. * Retrieve the field elements by given name
  222. *
  223. * @param {String} field The field name
  224. * @returns {null|jQuery[]}
  225. */
  226. getFieldElements: function(field) {
  227. var fields = this.$form.find('[name="' + field + '"]');
  228. return (fields.length == 0) ? null : fields;
  229. },
  230. /**
  231. * Validate the form
  232. */
  233. validate: function() {
  234. if (!this.options.fields) {
  235. return this;
  236. }
  237. this._disableSubmitButtons(true);
  238. for (var field in this.options.fields) {
  239. this.validateField(field);
  240. }
  241. this._submit();
  242. return this;
  243. },
  244. /**
  245. * Validate given field
  246. *
  247. * @param {String} field The field name
  248. */
  249. validateField: function(field) {
  250. var that = this,
  251. fields = this.$form.find('[name="' + field + '"]'),
  252. $field = $(fields[0]),
  253. validators = this.options.fields[field].validators,
  254. validatorName,
  255. validateResult;
  256. for (validatorName in validators) {
  257. if (this.dfds[field][validatorName]) {
  258. this.dfds[field][validatorName].reject();
  259. }
  260. // Don't validate field if it is already done
  261. if (this.results[field][validatorName] == this.STATUS_VALID || this.results[field][validatorName] == this.STATUS_INVALID) {
  262. continue;
  263. }
  264. this.results[field][validatorName] = this.STATUS_VALIDATING;
  265. validateResult = $.fn.bootstrapValidator.validators[validatorName].validate(this, $field, validators[validatorName]);
  266. if ('object' == typeof validateResult) {
  267. this.updateStatus($field, validatorName, this.STATUS_VALIDATING);
  268. this.dfds[field][validatorName] = validateResult;
  269. validateResult.done(function(isValid, v) {
  270. // v is validator name
  271. delete that.dfds[field][v];
  272. isValid ? that.updateStatus($field, v, that.STATUS_VALID)
  273. : that.updateStatus($field, v, that.STATUS_INVALID);
  274. });
  275. } else if ('boolean' == typeof validateResult) {
  276. validateResult ? this.updateStatus($field, validatorName, this.STATUS_VALID)
  277. : this.updateStatus($field, validatorName, this.STATUS_INVALID);
  278. }
  279. }
  280. },
  281. /**
  282. * Check the form validity
  283. *
  284. * @returns {Boolean}
  285. */
  286. isValid: function() {
  287. var field, validatorName;
  288. for (field in this.results) {
  289. for (validatorName in this.results[field]) {
  290. if (this.results[field][validatorName] == this.STATUS_NOT_VALIDATED || this.results[field][validatorName] == this.STATUS_VALIDATING) {
  291. return false;
  292. }
  293. if (this.results[field][validatorName] == this.STATUS_INVALID) {
  294. this.invalidField = field;
  295. return false;
  296. }
  297. }
  298. }
  299. return true;
  300. },
  301. /**
  302. * Update field status
  303. *
  304. * @param {jQuery} $field The field element
  305. * @param {String} validatorName
  306. * @param {String} status The status
  307. * Can be STATUS_VALIDATING, STATUS_INVALID, STATUS_VALID
  308. */
  309. updateStatus: function($field, validatorName, status) {
  310. var that = this,
  311. field = $field.attr('name'),
  312. validator = this.options.fields[field].validators[validatorName],
  313. message = validator.message || this.options.message,
  314. $parent = $field.parents('.form-group'),
  315. $errors = $parent.find('.help-block[data-bs-validator]');
  316. switch (status) {
  317. case this.STATUS_VALIDATING:
  318. this.results[field][validatorName] = this.STATUS_VALIDATING;
  319. this._disableSubmitButtons(true);
  320. $parent.removeClass('has-success').removeClass('has-error');
  321. // TODO: Show validating message
  322. $errors.filter('.help-block[data-bs-validator="' + validatorName + '"]').html(message).hide();
  323. if (this.options.feedbackIcons) {
  324. // Show "loading" icon
  325. $parent.find('.form-control-feedback').removeClass('glyphicon-ok').removeClass('glyphicon-remove').addClass('glyphicon-refresh').show();
  326. }
  327. break;
  328. case this.STATUS_INVALID:
  329. this.results[field][validatorName] = this.STATUS_INVALID;
  330. this._disableSubmitButtons(true);
  331. // Add has-error class to parent element
  332. $parent.removeClass('has-success').addClass('has-error');
  333. $errors.filter('[data-bs-validator="' + validatorName + '"]').html(message).show();
  334. if (this.options.feedbackIcons) {
  335. // Show "error" icon
  336. $parent.find('.form-control-feedback').removeClass('glyphicon-ok').removeClass('glyphicon-refresh').addClass('glyphicon-remove').show();
  337. }
  338. break;
  339. case this.STATUS_VALID:
  340. this.results[field][validatorName] = this.STATUS_VALID;
  341. // Hide error element
  342. $errors.filter('[data-bs-validator="' + validatorName + '"]').hide();
  343. // If the field is valid
  344. if ($errors.filter(function() {
  345. var display = $(this).css('display'), v = $(this).attr('data-bs-validator');
  346. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  347. }).length == 0
  348. ) {
  349. this._disableSubmitButtons(false);
  350. $parent.removeClass('has-error').addClass('has-success');
  351. // Show the "ok" icon
  352. if (this.options.feedbackIcons) {
  353. $parent.find('.form-control-feedback').removeClass('glyphicon-remove').removeClass('glyphicon-refresh').addClass('glyphicon-ok').show();
  354. }
  355. }
  356. break;
  357. default:
  358. break;
  359. }
  360. }
  361. };
  362. // Plugin definition
  363. $.fn.bootstrapValidator = function(options) {
  364. return this.each(function() {
  365. var $this = $(this), data = $this.data('bootstrapValidator');
  366. if (!data) {
  367. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  368. }
  369. if ('string' == typeof options) {
  370. data[options]();
  371. }
  372. });
  373. };
  374. // Available validators
  375. $.fn.bootstrapValidator.validators = {};
  376. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  377. }(window.jQuery));
  378. ;(function($) {
  379. $.fn.bootstrapValidator.validators.between = {
  380. /**
  381. * Return true if the input value is between (strictly or not) two given numbers
  382. *
  383. * @param {BootstrapValidator} validator The validator plugin instance
  384. * @param {jQuery} $field Field element
  385. * @param {Object} options Can consist of the following keys:
  386. * - min
  387. * - max
  388. * - inclusive [optional]: Can be true or false. Default is true
  389. * - message: The invalid message
  390. * @returns {Boolean}
  391. */
  392. validate: function(validator, $field, options) {
  393. var value = $field.val();
  394. if (value == '') {
  395. return true;
  396. }
  397. value = parseFloat(value);
  398. return (options.inclusive === true)
  399. ? (value > options.min && value < options.max)
  400. : (value >= options.min && value <= options.max);
  401. }
  402. };
  403. }(window.jQuery));
  404. ;(function($) {
  405. $.fn.bootstrapValidator.validators.callback = {
  406. /**
  407. * Return result from the callback method
  408. *
  409. * @param {BootstrapValidator} validator The validator plugin instance
  410. * @param {jQuery} $field Field element
  411. * @param {Object} options Can consist of the following keys:
  412. * - callback: The callback method that passes 2 parameters:
  413. * callback: function(fieldValue, validator) {
  414. * // fieldValue is the value of field
  415. * // validator is instance of BootstrapValidator
  416. * }
  417. * - message: The invalid message
  418. * @returns {Boolean|Deferred}
  419. */
  420. validate: function(validator, $field, options) {
  421. var value = $field.val();
  422. if (options.callback && 'function' == typeof options.callback) {
  423. var dfd = new $.Deferred();
  424. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  425. return dfd;
  426. }
  427. return true;
  428. }
  429. };
  430. }(window.jQuery));
  431. ;(function($) {
  432. $.fn.bootstrapValidator.validators.choice = {
  433. /**
  434. * Check if the number of checked boxes are less or more than a given number
  435. *
  436. * @param {BootstrapValidator} validator The validator plugin instance
  437. * @param {jQuery} $field Field element
  438. * @param {Object} options Consists of following keys:
  439. * - min
  440. * - max
  441. * At least one of two keys is required
  442. * @returns {Boolean}
  443. */
  444. validate: function(validator, $field, options) {
  445. var numChoices = validator
  446. .getFieldElements($field.attr('name'))
  447. .filter(':checked')
  448. .length;
  449. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  450. return false;
  451. }
  452. return true;
  453. }
  454. };
  455. }(window.jQuery));
  456. ;(function($) {
  457. $.fn.bootstrapValidator.validators.creditCard = {
  458. /**
  459. * Return true if the input value is valid credit card number
  460. * Based on https://gist.github.com/DiegoSalazar/4075533
  461. *
  462. * @param {BootstrapValidator} validator The validator plugin instance
  463. * @param {jQuery} $field Field element
  464. * @param {Object} options Can consist of the following key:
  465. * - message: The invalid message
  466. * @returns {Boolean}
  467. */
  468. validate: function(validator, $field, options) {
  469. var value = $field.val();
  470. if (value == '') {
  471. return true;
  472. }
  473. // Accept only digits, dashes or spaces
  474. if (/[^0-9-\s]+/.test(value)) {
  475. return false;
  476. }
  477. // The Luhn Algorithm
  478. // http://en.wikipedia.org/wiki/Luhn
  479. value = value.replace(/\D/g, '');
  480. var check = 0, digit = 0, even = false, length = value.length;
  481. for (var n = length - 1; n >= 0; n--) {
  482. digit = parseInt(value.charAt(n), 10);
  483. if (even) {
  484. if ((digit *= 2) > 9) {
  485. digit -= 9;
  486. }
  487. }
  488. check += digit;
  489. even = !even;
  490. }
  491. return (check % 10) == 0;
  492. }
  493. };
  494. }(window.jQuery));
  495. ;(function($) {
  496. $.fn.bootstrapValidator.validators.different = {
  497. /**
  498. * Return true if the input value is different with given field's value
  499. *
  500. * @param {BootstrapValidator} validator The validator plugin instance
  501. * @param {jQuery} $field Field element
  502. * @param {Object} options Consists of the following key:
  503. * - field: The name of field that will be used to compare with current one
  504. * @returns {Boolean}
  505. */
  506. validate: function(validator, $field, options) {
  507. var value = $field.val();
  508. if (value == '') {
  509. return true;
  510. }
  511. var compareWith = validator.getFieldElements(options.field);
  512. if (compareWith == null) {
  513. return true;
  514. }
  515. if (value != compareWith.val()) {
  516. validator.updateStatus(compareWith, 'different', validator.STATUS_VALID);
  517. return true;
  518. } else {
  519. return false;
  520. }
  521. }
  522. };
  523. }(window.jQuery));
  524. ;(function($) {
  525. $.fn.bootstrapValidator.validators.digits = {
  526. /**
  527. * Return true if the input value contains digits only
  528. *
  529. * @param {BootstrapValidator} validator Validate plugin instance
  530. * @param {jQuery} $field Field element
  531. * @param {Object} options
  532. * @returns {Boolean}
  533. */
  534. validate: function(validator, $field, options) {
  535. var value = $field.val();
  536. if (value == '') {
  537. return true;
  538. }
  539. return /^\d+$/.test(value);
  540. }
  541. }
  542. }(window.jQuery));
  543. ;(function($) {
  544. $.fn.bootstrapValidator.validators.emailAddress = {
  545. /**
  546. * Return true if and only if the input value is a valid email address
  547. *
  548. * @param {BootstrapValidator} validator Validate plugin instance
  549. * @param {jQuery} $field Field element
  550. * @param {Object} options
  551. * @returns {Boolean}
  552. */
  553. validate: function(validator, $field, options) {
  554. var value = $field.val();
  555. if (value == '') {
  556. return true;
  557. }
  558. // Email address regular expression
  559. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  560. 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,}))$/;
  561. return emailRegExp.test(value);
  562. }
  563. }
  564. }(window.jQuery));
  565. ;(function($) {
  566. $.fn.bootstrapValidator.validators.greaterThan = {
  567. /**
  568. * Return true if the input value is greater than or equals to given number
  569. *
  570. * @param {BootstrapValidator} validator Validate plugin instance
  571. * @param {jQuery} $field Field element
  572. * @param {Object} options Can consist of the following keys:
  573. * - value: The number used to compare to
  574. * - inclusive [optional]: Can be true or false. Default is true
  575. * - message: The invalid message
  576. * @returns {Boolean}
  577. */
  578. validate: function(validator, $field, options) {
  579. var value = $field.val();
  580. if (value == '') {
  581. return true;
  582. }
  583. value = parseFloat(value);
  584. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  585. }
  586. }
  587. }(window.jQuery));
  588. ;(function($) {
  589. $.fn.bootstrapValidator.validators.hexColor = {
  590. /**
  591. * Return true if the input value is a valid hex color
  592. *
  593. * @param {BootstrapValidator} validator The validator plugin instance
  594. * @param {jQuery} $field Field element
  595. * @param {Object} options Can consist of the following keys:
  596. * - message: The invalid message
  597. * @returns {Boolean}
  598. */
  599. validate: function(validator, $field, options) {
  600. var value = $field.val();
  601. if (value == '') {
  602. return true;
  603. }
  604. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  605. }
  606. };
  607. }(window.jQuery));
  608. ;(function($) {
  609. $.fn.bootstrapValidator.validators.identical = {
  610. /**
  611. * Check if input value equals to value of particular one
  612. *
  613. * @param {BootstrapValidator} validator The validator plugin instance
  614. * @param {jQuery} $field Field element
  615. * @param {Object} options Consists of the following key:
  616. * - field: The name of field that will be used to compare with current one
  617. * @returns {Boolean}
  618. */
  619. validate: function(validator, $field, options) {
  620. var value = $field.val();
  621. if (value == '') {
  622. return true;
  623. }
  624. var compareWith = validator.getFieldElements(options.field);
  625. if (compareWith == null) {
  626. return true;
  627. }
  628. if (value == compareWith.val()) {
  629. validator.updateStatus(compareWith, 'identical', validator.STATUS_VALID);
  630. return true;
  631. } else {
  632. return false;
  633. }
  634. }
  635. };
  636. }(window.jQuery));
  637. ;(function($) {
  638. $.fn.bootstrapValidator.validators.lessThan = {
  639. /**
  640. * Return true if the input value is less than or equal to given number
  641. *
  642. * @param {BootstrapValidator} validator The validator plugin instance
  643. * @param {jQuery} $field Field element
  644. * @param {Object} options Can consist of the following keys:
  645. * - value: The number used to compare to
  646. * - inclusive [optional]: Can be true or false. Default is true
  647. * - message: The invalid message
  648. * @returns {Boolean}
  649. */
  650. validate: function(validator, $field, options) {
  651. var value = $field.val();
  652. if (value == '') {
  653. return true;
  654. }
  655. value = parseFloat(value);
  656. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  657. }
  658. };
  659. }(window.jQuery));
  660. ;(function($) {
  661. $.fn.bootstrapValidator.validators.notEmpty = {
  662. /**
  663. * Check if input value is empty or not
  664. *
  665. * @param {BootstrapValidator} validator The validator plugin instance
  666. * @param {jQuery} $field Field element
  667. * @param {Object} options
  668. * @returns {Boolean}
  669. */
  670. validate: function(validator, $field, options) {
  671. var type = $field.attr('type');
  672. if ('radio' == type || 'checkbox' == type) {
  673. return validator
  674. .getFieldElements($field.attr('name'))
  675. .filter(':checked')
  676. .length > 0;
  677. }
  678. return $.trim($field.val()) != '';
  679. }
  680. };
  681. }(window.jQuery));
  682. ;(function($) {
  683. $.fn.bootstrapValidator.validators.regexp = {
  684. /**
  685. * Check if the element value matches given regular expression
  686. *
  687. * @param {BootstrapValidator} validator The validator plugin instance
  688. * @param {jQuery} $field Field element
  689. * @param {Object} options Consists of the following key:
  690. * - regexp: The regular expression you need to check
  691. * @returns {Boolean}
  692. */
  693. validate: function(validator, $field, options) {
  694. var value = $field.val();
  695. if (value == '') {
  696. return true;
  697. }
  698. return options.regexp.test(value);
  699. }
  700. };
  701. }(window.jQuery));
  702. ;(function($) {
  703. $.fn.bootstrapValidator.validators.remote = {
  704. /**
  705. * Request a remote server to check the input value
  706. *
  707. * @param {BootstrapValidator} validator Plugin instance
  708. * @param {jQuery} $field Field element
  709. * @param {Object} options Can consist of the following keys:
  710. * - url
  711. * - data [optional]: By default, it will take the value
  712. * {
  713. * <fieldName>: <fieldValue>
  714. * }
  715. * - message: The invalid message
  716. * @returns {Boolean|Deferred}
  717. */
  718. validate: function(validator, $field, options) {
  719. var value = $field.val();
  720. if (value == '') {
  721. return true;
  722. }
  723. var name = $field.attr('name'), data = options.data;
  724. if (data == null) {
  725. data = {};
  726. }
  727. data[name] = value;
  728. var dfd = new $.Deferred();
  729. var xhr = $.ajax({
  730. type: 'POST',
  731. url: options.url,
  732. dataType: 'json',
  733. data: data
  734. });
  735. xhr.then(function(response) {
  736. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  737. });
  738. dfd.fail(function() {
  739. xhr.abort();
  740. });
  741. return dfd;
  742. }
  743. };
  744. }(window.jQuery));
  745. ;(function($) {
  746. $.fn.bootstrapValidator.validators.stringLength = {
  747. /**
  748. * Check if the length of element value is less or more than given number
  749. *
  750. * @param {BootstrapValidator} validator The validator plugin instance
  751. * @param {jQuery} $field Field element
  752. * @param {Object} options Consists of following keys:
  753. * - min
  754. * - max
  755. * At least one of two keys is required
  756. * @returns {Boolean}
  757. */
  758. validate: function(validator, $field, options) {
  759. var value = $field.val();
  760. if (value == '') {
  761. return true;
  762. }
  763. var length = $.trim(value).length;
  764. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  765. return false;
  766. }
  767. return true;
  768. }
  769. };
  770. }(window.jQuery));
  771. ;(function($) {
  772. $.fn.bootstrapValidator.validators.uri = {
  773. /**
  774. * Return true if the input value is a valid URL
  775. *
  776. * @param {BootstrapValidator} validator The validator plugin instance
  777. * @param {jQuery} $field Field element
  778. * @param {Object} options
  779. * @returns {Boolean}
  780. */
  781. validate: function(validator, $field, options) {
  782. var value = $field.val();
  783. if (value == '') {
  784. return true;
  785. }
  786. // Credit to https://gist.github.com/dperini/729294
  787. //
  788. // Regular Expression for URL validation
  789. //
  790. // Author: Diego Perini
  791. // Updated: 2010/12/05
  792. //
  793. // the regular expression composed & commented
  794. // could be easily tweaked for RFC compliance,
  795. // it was expressly modified to fit & satisfy
  796. // these test for an URL shortener:
  797. //
  798. // http://mathiasbynens.be/demo/url-regex
  799. //
  800. // Notes on possible differences from a standard/generic validation:
  801. //
  802. // - utf-8 char class take in consideration the full Unicode range
  803. // - TLDs have been made mandatory so single names like "localhost" fails
  804. // - protocols have been restricted to ftp, http and https only as requested
  805. //
  806. // Changes:
  807. //
  808. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  809. // first and last IP address of each class is considered invalid
  810. // (since they are broadcast/network addresses)
  811. //
  812. // - Added exclusion of private, reserved and/or local networks ranges
  813. //
  814. // Compressed one-line versions:
  815. //
  816. // Javascript version
  817. //
  818. // /^(?:(?: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
  819. //
  820. // PHP version
  821. //
  822. // _^(?:(?: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
  823. var urlExp = new RegExp(
  824. "^" +
  825. // protocol identifier
  826. "(?:(?:https?|ftp)://)" +
  827. // user:pass authentication
  828. "(?:\\S+(?::\\S*)?@)?" +
  829. "(?:" +
  830. // IP address exclusion
  831. // private & local networks
  832. "(?!10(?:\\.\\d{1,3}){3})" +
  833. "(?!127(?:\\.\\d{1,3}){3})" +
  834. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  835. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  836. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  837. // IP address dotted notation octets
  838. // excludes loopback network 0.0.0.0
  839. // excludes reserved space >= 224.0.0.0
  840. // excludes network & broacast addresses
  841. // (first & last IP address of each class)
  842. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  843. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  844. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  845. "|" +
  846. // host name
  847. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  848. // domain name
  849. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  850. // TLD identifier
  851. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  852. ")" +
  853. // port number
  854. "(?::\\d{2,5})?" +
  855. // resource path
  856. "(?:/[^\\s]*)?" +
  857. "$", "i"
  858. );
  859. return urlExp.test(value);
  860. }
  861. };
  862. }(window.jQuery));
  863. ;(function($) {
  864. $.fn.bootstrapValidator.validators.zipCode = {
  865. /**
  866. * Return true if and only if the input value is a valid country zip code
  867. *
  868. * @param {BootstrapValidator} validator The validator plugin instance
  869. * @param {jQuery} $field Field element
  870. * @param {Object} options Consist of key:
  871. * - country: The ISO 3166 country code
  872. *
  873. * Currently it supports the following countries:
  874. * - US (United State)
  875. * - DK (Denmark)
  876. * - SE (Sweden)
  877. *
  878. * @returns {Boolean}
  879. */
  880. validate: function(validateInstance, $field, options) {
  881. var value = $field.val();
  882. if (value == '' || !options.country) {
  883. return true;
  884. }
  885. switch (options.country.toUpperCase()) {
  886. case 'DK':
  887. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  888. case 'SE':
  889. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  890. case 'US':
  891. default:
  892. return /^\d{5}([\-]\d{4})?$/.test(value);
  893. }
  894. }
  895. };
  896. }(window.jQuery));