bootstrapValidator.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  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
  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 field = $field.attr('name'),
  311. validator = this.options.fields[field].validators[validatorName],
  312. message = validator.message || this.options.message,
  313. $parent = $field.parents('.form-group'),
  314. $errors = $parent.find('.help-block[data-bs-validator]');
  315. switch (status) {
  316. case this.STATUS_VALIDATING:
  317. this.results[field][validatorName] = this.STATUS_VALIDATING;
  318. this._disableSubmitButtons(true);
  319. $parent.removeClass('has-success').removeClass('has-error');
  320. // TODO: Show validating message
  321. $errors.filter('.help-block[data-bs-validator="' + validatorName + '"]').html(message).hide();
  322. if (this.options.feedbackIcons) {
  323. // Show "loading" icon
  324. $parent.find('.form-control-feedback').removeClass('glyphicon-ok').removeClass('glyphicon-remove').addClass('glyphicon-refresh').show();
  325. }
  326. break;
  327. case this.STATUS_INVALID:
  328. this.results[field][validatorName] = this.STATUS_INVALID;
  329. this._disableSubmitButtons(true);
  330. // Add has-error class to parent element
  331. $parent.removeClass('has-success').addClass('has-error');
  332. $errors
  333. .filter('[data-bs-validator="' + validatorName + '"]')
  334. .html(message)
  335. .show();
  336. if (this.options.feedbackIcons) {
  337. // Show "error" icon
  338. $parent.find('.form-control-feedback').removeClass('glyphicon-ok').removeClass('glyphicon-refresh').addClass('glyphicon-remove').show();
  339. }
  340. break;
  341. case this.STATUS_VALID:
  342. this.results[field][validatorName] = this.STATUS_VALID;
  343. // Hide error element
  344. $errors.filter('[data-bs-validator="' + validatorName + '"]').hide();
  345. // If the field is valid
  346. var that = this;
  347. if ($errors.filter(function() {
  348. var display = $(this).css('display'), v = $(this).attr('data-bs-validator');
  349. return ('block' == display) || (that.results[field][v] != that.STATUS_VALID);
  350. }).length == 0
  351. ) {
  352. this._disableSubmitButtons(false);
  353. $parent.removeClass('has-error').addClass('has-success');
  354. // Show the "ok" icon
  355. if (this.options.feedbackIcons) {
  356. $parent.find('.form-control-feedback').removeClass('glyphicon-remove').removeClass('glyphicon-refresh').addClass('glyphicon-ok').show();
  357. }
  358. }
  359. break;
  360. default:
  361. break;
  362. }
  363. }
  364. };
  365. // Plugin definition
  366. $.fn.bootstrapValidator = function(options) {
  367. return this.each(function() {
  368. var $this = $(this), data = $this.data('bootstrapValidator');
  369. if (!data) {
  370. $this.data('bootstrapValidator', (data = new BootstrapValidator(this, options)));
  371. }
  372. if ('string' == typeof options) {
  373. data[options]();
  374. }
  375. });
  376. };
  377. // Available validators
  378. $.fn.bootstrapValidator.validators = {};
  379. $.fn.bootstrapValidator.Constructor = BootstrapValidator;
  380. }(window.jQuery));
  381. ;(function($) {
  382. $.fn.bootstrapValidator.validators.between = {
  383. /**
  384. * Return true if the input value is between (strictly or not) two given numbers
  385. *
  386. * @param {BootstrapValidator} validator The validator plugin instance
  387. * @param {jQuery} $field Field element
  388. * @param {Object} options Can consist of the following keys:
  389. * - min
  390. * - max
  391. * - inclusive [optional]: Can be true or false. Default is true
  392. * - message: The invalid message
  393. * @returns {Boolean}
  394. */
  395. validate: function(validator, $field, options) {
  396. var value = $field.val();
  397. if (value == '') {
  398. return true;
  399. }
  400. value = parseFloat(value);
  401. return (options.inclusive === true)
  402. ? (value > options.min && value < options.max)
  403. : (value >= options.min && value <= options.max);
  404. }
  405. };
  406. }(window.jQuery));
  407. ;(function($) {
  408. $.fn.bootstrapValidator.validators.callback = {
  409. /**
  410. * Return result from the callback method
  411. *
  412. * @param {BootstrapValidator} validator The validator plugin instance
  413. * @param {jQuery} $field Field element
  414. * @param {Object} options Can consist of the following keys:
  415. * - callback: The callback method that passes 2 parameters:
  416. * callback: function(fieldValue, validator) {
  417. * // fieldValue is the value of field
  418. * // validator is instance of BootstrapValidator
  419. * }
  420. * - message: The invalid message
  421. * @returns {Boolean|Deferred}
  422. */
  423. validate: function(validator, $field, options) {
  424. var value = $field.val();
  425. if (options.callback && 'function' == typeof options.callback) {
  426. var dfd = new $.Deferred();
  427. dfd.resolve(options.callback.call(this, value, validator), 'callback');
  428. return dfd;
  429. }
  430. return true;
  431. }
  432. };
  433. }(window.jQuery));
  434. ;(function($) {
  435. $.fn.bootstrapValidator.validators.choice = {
  436. /**
  437. * Check if the number of checked boxes are less or more than a given number
  438. *
  439. * @param {BootstrapValidator} validator The validator plugin instance
  440. * @param {jQuery} $field Field element
  441. * @param {Object} options Consists of following keys:
  442. * - min
  443. * - max
  444. * At least one of two keys is required
  445. * @returns {Boolean}
  446. */
  447. validate: function(validator, $field, options) {
  448. var numChoices = validator
  449. .getFieldElements($field.attr('name'))
  450. .filter(':checked')
  451. .length;
  452. if ((options.min && numChoices < options.min) || (options.max && numChoices > options.max)) {
  453. return false;
  454. }
  455. return true;
  456. }
  457. };
  458. }(window.jQuery));
  459. ;(function($) {
  460. $.fn.bootstrapValidator.validators.creditCard = {
  461. /**
  462. * Return true if the input value is valid credit card number
  463. * Based on https://gist.github.com/DiegoSalazar/4075533
  464. *
  465. * @param {BootstrapValidator} validator The validator plugin instance
  466. * @param {jQuery} $field Field element
  467. * @param {Object} options Can consist of the following key:
  468. * - message: The invalid message
  469. * @returns {Boolean}
  470. */
  471. validate: function(validator, $field, options) {
  472. var value = $field.val();
  473. if (value == '') {
  474. return true;
  475. }
  476. // Accept only digits, dashes or spaces
  477. if (/[^0-9-\s]+/.test(value)) {
  478. return false;
  479. }
  480. // The Luhn Algorithm
  481. // http://en.wikipedia.org/wiki/Luhn
  482. value = value.replace(/\D/g, '');
  483. var check = 0, digit = 0, even = false, length = value.length;
  484. for (var n = length - 1; n >= 0; n--) {
  485. digit = parseInt(value.charAt(n), 10);
  486. if (even) {
  487. if ((digit *= 2) > 9) {
  488. digit -= 9;
  489. }
  490. }
  491. check += digit;
  492. even = !even;
  493. }
  494. return (check % 10) == 0;
  495. }
  496. };
  497. }(window.jQuery));
  498. ;(function($) {
  499. $.fn.bootstrapValidator.validators.different = {
  500. /**
  501. * Return true if the input value is different with given field's value
  502. *
  503. * @param {BootstrapValidator} validator The validator plugin instance
  504. * @param {jQuery} $field Field element
  505. * @param {Object} options Consists of the following key:
  506. * - field: The name of field that will be used to compare with current one
  507. * @returns {Boolean}
  508. */
  509. validate: function(validator, $field, options) {
  510. var value = $field.val();
  511. if (value == '') {
  512. return true;
  513. }
  514. var compareWith = validator.getFieldElements(options.field);
  515. if (compareWith == null) {
  516. return true;
  517. }
  518. if (value != compareWith.val()) {
  519. validator.updateStatus(compareWith, 'different', validator.STATUS_VALID);
  520. return true;
  521. } else {
  522. return false;
  523. }
  524. }
  525. };
  526. }(window.jQuery));
  527. ;(function($) {
  528. $.fn.bootstrapValidator.validators.digits = {
  529. /**
  530. * Return true if the input value contains digits only
  531. *
  532. * @param {BootstrapValidator} validator Validate plugin instance
  533. * @param {jQuery} $field Field element
  534. * @param {Object} options
  535. * @returns {Boolean}
  536. */
  537. validate: function(validator, $field, options) {
  538. var value = $field.val();
  539. if (value == '') {
  540. return true;
  541. }
  542. return /^\d+$/.test(value);
  543. }
  544. }
  545. }(window.jQuery));
  546. ;(function($) {
  547. $.fn.bootstrapValidator.validators.emailAddress = {
  548. /**
  549. * Return true if and only if the input value is a valid email address
  550. *
  551. * @param {BootstrapValidator} validator Validate plugin instance
  552. * @param {jQuery} $field Field element
  553. * @param {Object} options
  554. * @returns {Boolean}
  555. */
  556. validate: function(validator, $field, options) {
  557. var value = $field.val();
  558. if (value == '') {
  559. return true;
  560. }
  561. // Email address regular expression
  562. // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
  563. 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,}))$/;
  564. return emailRegExp.test(value);
  565. }
  566. }
  567. }(window.jQuery));
  568. ;(function($) {
  569. $.fn.bootstrapValidator.validators.greaterThan = {
  570. /**
  571. * Return true if the input value is greater than or equals to given number
  572. *
  573. * @param {BootstrapValidator} validator Validate plugin instance
  574. * @param {jQuery} $field Field element
  575. * @param {Object} options Can consist of the following keys:
  576. * - value: The number used to compare to
  577. * - inclusive [optional]: Can be true or false. Default is true
  578. * - message: The invalid message
  579. * @returns {Boolean}
  580. */
  581. validate: function(validator, $field, options) {
  582. var value = $field.val();
  583. if (value == '') {
  584. return true;
  585. }
  586. value = parseFloat(value);
  587. return (options.inclusive === true) ? (value > options.value) : (value >= options.value);
  588. }
  589. }
  590. }(window.jQuery));
  591. ;(function($) {
  592. $.fn.bootstrapValidator.validators.hexColor = {
  593. /**
  594. * Return true if the input value is a valid hex color
  595. *
  596. * @param {BootstrapValidator} validator The validator plugin instance
  597. * @param {jQuery} $field Field element
  598. * @param {Object} options Can consist of the following keys:
  599. * - message: The invalid message
  600. * @returns {Boolean}
  601. */
  602. validate: function(validator, $field, options) {
  603. var value = $field.val();
  604. if (value == '') {
  605. return true;
  606. }
  607. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
  608. }
  609. };
  610. }(window.jQuery));
  611. ;(function($) {
  612. $.fn.bootstrapValidator.validators.identical = {
  613. /**
  614. * Check if input value equals to value of particular one
  615. *
  616. * @param {BootstrapValidator} validator The validator plugin instance
  617. * @param {jQuery} $field Field element
  618. * @param {Object} options Consists of the following key:
  619. * - field: The name of field that will be used to compare with current one
  620. * @returns {Boolean}
  621. */
  622. validate: function(validator, $field, options) {
  623. var value = $field.val();
  624. if (value == '') {
  625. return true;
  626. }
  627. var compareWith = validator.getFieldElements(options.field);
  628. if (compareWith == null) {
  629. return true;
  630. }
  631. if (value == compareWith.val()) {
  632. validator.updateStatus(compareWith, 'identical', validator.STATUS_VALID);
  633. return true;
  634. } else {
  635. return false;
  636. }
  637. }
  638. };
  639. }(window.jQuery));
  640. ;(function($) {
  641. $.fn.bootstrapValidator.validators.lessThan = {
  642. /**
  643. * Return true if the input value is less than or equal to given number
  644. *
  645. * @param {BootstrapValidator} validator The validator plugin instance
  646. * @param {jQuery} $field Field element
  647. * @param {Object} options Can consist of the following keys:
  648. * - value: The number used to compare to
  649. * - inclusive [optional]: Can be true or false. Default is true
  650. * - message: The invalid message
  651. * @returns {Boolean}
  652. */
  653. validate: function(validator, $field, options) {
  654. var value = $field.val();
  655. if (value == '') {
  656. return true;
  657. }
  658. value = parseFloat(value);
  659. return (options.inclusive === true) ? (value < options.value) : (value <= options.value);
  660. }
  661. };
  662. }(window.jQuery));
  663. ;(function($) {
  664. $.fn.bootstrapValidator.validators.notEmpty = {
  665. /**
  666. * Check if input value is empty or not
  667. *
  668. * @param {BootstrapValidator} validator The validator plugin instance
  669. * @param {jQuery} $field Field element
  670. * @param {Object} options
  671. * @returns {Boolean}
  672. */
  673. validate: function(validator, $field, options) {
  674. var type = $field.attr('type');
  675. if ('radio' == type || 'checkbox' == type) {
  676. return validator
  677. .getFieldElements($field.attr('name'))
  678. .filter(':checked')
  679. .length > 0;
  680. }
  681. return $.trim($field.val()) != '';
  682. }
  683. };
  684. }(window.jQuery));
  685. ;(function($) {
  686. $.fn.bootstrapValidator.validators.regexp = {
  687. /**
  688. * Check if the element value matches given regular expression
  689. *
  690. * @param {BootstrapValidator} validator The validator plugin instance
  691. * @param {jQuery} $field Field element
  692. * @param {Object} options Consists of the following key:
  693. * - regexp: The regular expression you need to check
  694. * @returns {Boolean}
  695. */
  696. validate: function(validator, $field, options) {
  697. var value = $field.val();
  698. if (value == '') {
  699. return true;
  700. }
  701. return options.regexp.test(value);
  702. }
  703. };
  704. }(window.jQuery));
  705. ;(function($) {
  706. $.fn.bootstrapValidator.validators.remote = {
  707. /**
  708. * Request a remote server to check the input value
  709. *
  710. * @param {BootstrapValidator} validator Plugin instance
  711. * @param {jQuery} $field Field element
  712. * @param {Object} options Can consist of the following keys:
  713. * - url
  714. * - data [optional]: By default, it will take the value
  715. * {
  716. * <fieldName>: <fieldValue>
  717. * }
  718. * - message: The invalid message
  719. * @returns {Boolean|Deferred}
  720. */
  721. validate: function(validator, $field, options) {
  722. var value = $field.val();
  723. if (value == '') {
  724. return true;
  725. }
  726. var name = $field.attr('name'), data = options.data;
  727. if (data == null) {
  728. data = {};
  729. }
  730. data[name] = value;
  731. var dfd = new $.Deferred();
  732. var xhr = $.ajax({
  733. type: 'POST',
  734. url: options.url,
  735. dataType: 'json',
  736. data: data
  737. });
  738. xhr.then(function(response) {
  739. dfd.resolve(response.valid === true || response.valid === 'true', 'remote');
  740. });
  741. dfd.fail(function() {
  742. xhr.abort();
  743. });
  744. return dfd;
  745. }
  746. };
  747. }(window.jQuery));
  748. ;(function($) {
  749. $.fn.bootstrapValidator.validators.stringLength = {
  750. /**
  751. * Check if the length of element value is less or more than given number
  752. *
  753. * @param {BootstrapValidator} validator The validator plugin instance
  754. * @param {jQuery} $field Field element
  755. * @param {Object} options Consists of following keys:
  756. * - min
  757. * - max
  758. * At least one of two keys is required
  759. * @returns {Boolean}
  760. */
  761. validate: function(validator, $field, options) {
  762. var value = $field.val();
  763. if (value == '') {
  764. return true;
  765. }
  766. var length = $.trim(value).length;
  767. if ((options.min && length < options.min) || (options.max && length > options.max)) {
  768. return false;
  769. }
  770. return true;
  771. }
  772. };
  773. }(window.jQuery));
  774. ;(function($) {
  775. $.fn.bootstrapValidator.validators.uri = {
  776. /**
  777. * Return true if the input value is a valid URL
  778. *
  779. * @param {BootstrapValidator} validator The validator plugin instance
  780. * @param {jQuery} $field Field element
  781. * @param {Object} options
  782. * @returns {Boolean}
  783. */
  784. validate: function(validator, $field, options) {
  785. var value = $field.val();
  786. if (value == '') {
  787. return true;
  788. }
  789. // Credit to https://gist.github.com/dperini/729294
  790. //
  791. // Regular Expression for URL validation
  792. //
  793. // Author: Diego Perini
  794. // Updated: 2010/12/05
  795. //
  796. // the regular expression composed & commented
  797. // could be easily tweaked for RFC compliance,
  798. // it was expressly modified to fit & satisfy
  799. // these test for an URL shortener:
  800. //
  801. // http://mathiasbynens.be/demo/url-regex
  802. //
  803. // Notes on possible differences from a standard/generic validation:
  804. //
  805. // - utf-8 char class take in consideration the full Unicode range
  806. // - TLDs have been made mandatory so single names like "localhost" fails
  807. // - protocols have been restricted to ftp, http and https only as requested
  808. //
  809. // Changes:
  810. //
  811. // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
  812. // first and last IP address of each class is considered invalid
  813. // (since they are broadcast/network addresses)
  814. //
  815. // - Added exclusion of private, reserved and/or local networks ranges
  816. //
  817. // Compressed one-line versions:
  818. //
  819. // Javascript version
  820. //
  821. // /^(?:(?: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
  822. //
  823. // PHP version
  824. //
  825. // _^(?:(?: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
  826. var urlExp = new RegExp(
  827. "^" +
  828. // protocol identifier
  829. "(?:(?:https?|ftp)://)" +
  830. // user:pass authentication
  831. "(?:\\S+(?::\\S*)?@)?" +
  832. "(?:" +
  833. // IP address exclusion
  834. // private & local networks
  835. "(?!10(?:\\.\\d{1,3}){3})" +
  836. "(?!127(?:\\.\\d{1,3}){3})" +
  837. "(?!169\\.254(?:\\.\\d{1,3}){2})" +
  838. "(?!192\\.168(?:\\.\\d{1,3}){2})" +
  839. "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
  840. // IP address dotted notation octets
  841. // excludes loopback network 0.0.0.0
  842. // excludes reserved space >= 224.0.0.0
  843. // excludes network & broacast addresses
  844. // (first & last IP address of each class)
  845. "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
  846. "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
  847. "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
  848. "|" +
  849. // host name
  850. "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
  851. // domain name
  852. "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
  853. // TLD identifier
  854. "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
  855. ")" +
  856. // port number
  857. "(?::\\d{2,5})?" +
  858. // resource path
  859. "(?:/[^\\s]*)?" +
  860. "$", "i"
  861. );
  862. return urlExp.test(value);
  863. }
  864. };
  865. }(window.jQuery));
  866. ;(function($) {
  867. $.fn.bootstrapValidator.validators.zipCode = {
  868. /**
  869. * Return true if and only if the input value is a valid country zip code
  870. *
  871. * @param {BootstrapValidator} validator The validator plugin instance
  872. * @param {jQuery} $field Field element
  873. * @param {Object} options Consist of key:
  874. * - country: The ISO 3166 country code
  875. *
  876. * Currently it supports the following countries:
  877. * - US (United State)
  878. * - DK (Denmark)
  879. * - SE (Sweden)
  880. *
  881. * @returns {Boolean}
  882. */
  883. validate: function(validateInstance, $field, options) {
  884. var value = $field.val();
  885. if (value == '' || !options.country) {
  886. return true;
  887. }
  888. switch (options.country.toUpperCase()) {
  889. case 'DK':
  890. return /^(DK(-|\s)?)?\d{4}$/i.test(value);
  891. case 'SE':
  892. return /^(S-)?\d{3}\s?\d{2}$/i.test(value);
  893. case 'US':
  894. default:
  895. return /^\d{5}([\-]\d{4})?$/.test(value);
  896. }
  897. }
  898. };
  899. }(window.jQuery));